Lists, Ranges and Loops

Contents

Lists, Ranges and Loops#

Python Programming for Engineers#

Tel-Aviv University / 0509-1820 / Fall 2025-2026#

Last week’s highlights#

  • Memory and variables

  • Different variable types (int, float, str, bool)

  • Different operations for different types

  • Functions

def foo(param1, param2, ..):
    ...
    return res
  • if-else statements

if expression: 
    statement1
else:
    statement2

Agenda#

Lists

Ranges

Loops

  • types of loops: while, for
  • Other loop statements: break, continue
  • The phonebook of Rick

Lists#

  • An ordered collection of elements

  • Each element in a list can be of any type

Basic operations#

# student: name, age, height, SAT
student = ['Rick', 81, 1.83, 9000]

print(student)
['Rick', 81, 1.83, 9000]
student[3]
9000
len(student)
4
student[0:-1]
['Rick', 81, 1.83]
student[::-1]
[9000, 1.83, 81, 'Rick']
student[6:10:2] # What happens here?
[]
my_list = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']
new_list = my_list[::2]
print(my_list)
print(new_list)
['Rick', 'Morty', 'Beth', 'Jerry', 'Summer']
['Rick', 'Beth', 'Summer']
students = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']
print(students)
['Rick', 'Morty', 'Beth', 'Jerry', 'Summer']
students[1:5]=["Tiny Rick!", "Rick c-135", "Rick c-135", "Rick c-135"]
print(students)
['Rick', 'Tiny Rick!', 'Rick c-135', 'Rick c-135', 'Rick c-135']
students[2]+=" (a.k.a evil Rick)"
print(students)
['Rick', 'Tiny Rick!', 'Rick c-135 (a.k.a evil Rick)', 'Rick c-135', 'Rick c-135']

Example 1: Minimal result#

Given two lists, st1 and lst2, compute for each the sum of the list divided by the middle value, and print the smaller of the two results.#

Plan#

  1. Calculate sum divided by middle for lst1

  2. Calculate sum divided by middle for lst2

  3. Print the smaller one

Pseudo code#

  1. res1 \(\leftarrow\) sum_div_middle(lst1)

  2. res2 \(\leftarrow\) sum_div_middle(lst2)

  3. print min(res1, res2)

Implement pseudo code:#

def sum_div_middle(lst):
    return sum(lst) / lst[len(lst)//2]
res1=sum_div_middle([1,3,7])
res2=sum_div_middle([100,30,7])
print(min(res1,res2))
3.6666666666666665

Nested lists/Matrix#

mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
print(mat)
[['m', 'a', 't', 'R'], ['i', 'c', 'k', 's']]
print(len(mat))
2
print(len(mat[1]))
4
print(mat[1][2]) 
k

And what about mat[2][1]?

Example 2: Element-wise product#

  • For a pair of 2x2 matrices, multiply each number in the first matrix with its corresponding number in the second matrix

  • Corresponding number = the number that lies in the same position

m=[[2,2], [1,3]]
n=[[4,2], [9,2]]

result=[[],[]]

i=0; j=0
result[i].append(m[i][j]*n[i][j])

i=0; j=1
result[i].append(m[i][j]*n[i][j])

i=1; j=0
result[i].append(m[i][j]*n[i][j])

i=1; j=1
result[i].append(m[i][j]*n[i][j])


print(result)
[[8, 4], [9, 6]]

List’s methods#

  • Applied using the dot notation: variable_name.function_name()

  • Might change the original object

    • Strings: Immutable

    • Lists: Mutable

Partial list of methods#

method

description

lst.append(item)

append an item to the end of the list

lst.count(val)

return the number of occurrences of val

lst.extend(another_lst)

extend list by appending items from another list

lst.index(val)

return first index of val

lst.insert(index, item)

insert an item before index

lst.pop(index)

remove the item at location index and return it (remove last element if index is omitted)

lst.remove(val)

remove first occurrence of a val

lst.reverse()

reverse the list (in place)

lst.sort()

sort the list (in place)

*bolded does not change the list

Other list’s function:#

function

description

len()

returns the list’s length

sum()

returns a sum of all list elements

min()

returns the minimal element

max()

returns the maximal element

sorted()

returns a sorted copy of the list

in

returns True if element in list (e.g. 1 in lst)

Sorting lists#

a = [3,7,1]
b = sorted(a)
print(a)
print(b)
[3, 7, 1]
[1, 3, 7]
a = [3,7,1]
b = a.sort()
print(a)
print(b)
[1, 3, 7]
None

Iterable#

  • Represent a sequence of some kind

    • What kind of sequence did we see so far? Strings, Lists

Range#

  • Another iterable range(from, to, step) returns:
    from, from+step, from+2*step,…, from+i*step until (and not including) to is reached.

list(range(7))
[0, 1, 2, 3, 4, 5, 6]
list(range(3,7))
[3, 4, 5, 6]
list(range(7, 3, -1))
[7, 6, 5, 4]
list(range(-3,7,1))
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
list(range(1, 7, -3))
[]
list(range(0, 137, 0))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[26], line 1
----> 1 list(range(0, 137, 0))

ValueError: range() arg 3 must not be zero

For loops#

Syntax#

for element in iterable:
    statement1
    statement2
    
rest of code

Iteration can also be done on a string#

name = "Rick"
for letter in name:
    print("Give me", letter)
print("What did we get?", name)
Give me R
Give me i
Give me c
Give me k
What did we get? Rick

Put zeros instead each even element#

# Modify the list
lst = [1,2,3,4,7]
for i in range(len(lst)):
    if lst[i] % 2 == 0:
        lst[i] = 0
print(lst)
[1, 0, 3, 0, 7]
# The This is NOT equivalent! Does not modify the list...
lst = [1,2,3,4,7]
for elem in lst:
    if elem % 2 == 0:
        elem = 0
print(lst)
[1, 2, 3, 4, 7]

Slide 55

Infinite for loop#

# Do not run this code
x=[1]
for a in x:
    x.append(1)
    print(x)

Avoid changing the list on which you iterate! (may cause all kind of problem, including infinite loops)#

Example #3: concatenate all characters in a matrix into a single string#

mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
# Write your code here
mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
    for j in range(num_columns):
        my_string+=mat[i][j]
print(my_string)
matRicks

Try this with Python Tutor

Slide 56

while loops#

Syntax#

while expression: ## expression is either True or False
    statement1
    statement2
    
rest of code

Infinite loop#

# Do not run this code
i = 1
while i < 137:
    print(i)

break and continue statements#

  • Interrupts the nearest enclosing loop

  • Jointly used with an if statement

break statement – breaking loops#

lst = [4, 2, -6, 3,-9]
for elem in lst:
    if elem < 0: 
        print("First negative number is", elem)
        break
print("done!")
First negative number is -6
done!
x=0
while x<30: 
    x+=1
    if not x % 10:
        break
    print(x, end='\t')
1	2	3	4	5	6	7	8	9	

continue statement – Skipping loops#

x=0
while x<30: 
    x+=1
    if not x % 10:
        continue
    print(x, end='\t')
1	2	3	4	5	6	7	8	9	11	12	13	14	15	16	17	18	19	21	22	23	24	25	26	27	28	29	

Loops - for or while?#

In most cases it is more natural to use for
In some cases it is better to use while

  • for:

    • Predefined number of iterations

    • No need to initialize or advance the loop variable

  • while:

    • Unknown number of iterations

    • Can specify a stop condition

Self learning#

Exercise 1: List methods#

What will be printed?#

students=['Rick', 'Tiny Rick!', 'Beth', 'Jerry', 'Summer', 'Jessica', 'Rick', 'Rick']
x = students.pop(-1)
if x in students[:len(students)//2] and x in students[len(students)//2:]:
    students.remove(x)
    students.remove(x)
    
if x in students[:len(students)//2] or x in students[len(students)//2:]:
    students.remove(x)

print("Rick" in students)
False

Exercise 2: Multiplication chart#

Solution#

for i in range(1,11):
    for j in range(1,11):
        print(i*j, end ="\t")
    print()
1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
4	8	12	16	20	24	28	32	36	40	
5	10	15	20	25	30	35	40	45	50	
6	12	18	24	30	36	42	48	54	60	
7	14	21	28	35	42	49	56	63	70	
8	16	24	32	40	48	56	64	72	80	
9	18	27	36	45	54	63	72	81	90	
10	20	30	40	50	60	70	80	90	100	

Exercise 3: Unique list of numbers#

Write a function that receives a list of number, and returns a list where each number from the original list appears exactly once.#

[1,3,3,1,7,7,7,1,3] \(\rightarrow\) [1,3,7]

lst = [1,3,3,1,7,7,7,1,3]
## You code here

Solution#

lst = [1,3,3,1,7,7,7,1,3]
uniques = []
for x in lst: 
    if x in uniques: 
        continue 
    uniques.append(x)
print(uniques)
[1, 3, 7]

Exercise 4: The phone book of Rick#

  • We want to develop an application for managing the Contacts of Ricks

  • It will contain a database

  • A list of contacts

  • Each contact is a list in the format [name, phone]

  • Functionality

  • Find contact(s) by full name or prefix

  • Add contact

  • Remove contact

phone_book = [['Morty','1111'], ['Beth', '2222'], ['rick c-138', '8888'], ['rick c-139', '9999']]

Retrieve the number for a given person#

name = 'rick' ## Change the value here
### Write your code here

if found:
    print("Name:", name , "Phone:", phone)
else:
    print("Cannot find", name , "in contact list.")

Solution#

name = 'rick' ## Change the value here
found = False
phone = ""
for contact in phone_book:
    if contact[0] == name:
        found = True
        phone = contact[1]
        break
if found:
    print("Name:", name , "Phone:", phone)
else:
    print("Cannot find", name , "in contact list.")
Cannot find rick in contact list.

Add a contact#

name = 'rick'# Change the value here
num = 1234
phone_book.append([name, num])
print(phone_book)
[['Morty', '1111'], ['Beth', '2222'], ['rick c-138', '8888'], ['rick c-139', '9999'], ['rick', 1234]]

Remove a contact#

name = 'rick'# Change the value here
found = False
for contact in phone_book:
    if contact[0] == name:
        ###  Write your code here

if not found:
    print("Cannot find the contact", "name")

Solution#

name = 'rick'# Change the value here
found = False
for contact in phone_book:
    if contact[0] == name:
        phone_book.remove(contact)
        print(f'The contact {name} was deleted')
        found = True
        break

if not found:
    print("Cannot find the contact", name)
The contact rick was deleted

Search for all contacts with given prefix.#

Ignore character case (aka, case insensitive).#

prefix = "Rick"
### Write your code here
prefix = "Rick"
prefix = prefix.lower()
for contact in phone_book:    
    if contact[0].lower().startswith(prefix):        
        print("Name:", contact[0], "Phone:", contact[1])
Name: rick c-138 Phone: 8888
Name: rick c-139 Phone: 9999