Lists and Ranges#

Last weeks’ 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

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