6 Tuples listes
6 Tuples listes
LAMBDA FUNCTIONS,
TUPLES and LISTS
def apply(criteria,n):
"""
* criteria: function that takes in a number and returns a bool
* n: an int
Returns how many ints from 0 to n (inclusive) match the
criteria (i.e. return True when run with criteria) """
count = 0
for i in range(n+1):
if criteria(i):
count += 1
return count
def is_even(x):
return x%2==0
print(apply(is_even,10))
1
13/12/2024
ANONYMOUS FUNCTIONS
lambda x: x%2 == 0
Body of lambda
parameter Note no return keyword
ANONYMOUS FUNCTIONS
2
13/12/2024
Global environment
3
13/12/2024
4
13/12/2024
lambda x: x**2
environment
x 3
lambda x: x**2
environment
x 3
Returns 9
5
13/12/2024
6
13/12/2024
TUPLES
7
13/12/2024
TUPLES
t = (2, "mit", 3)
t[0] evaluates to 2
(2,"mit",3) + (5,6)evaluates to a new tuple(2,"mit",3,5,6)
t[1:2] slice tuple, evaluates to ("mit",)
t[1:3] slice tuple, evaluates to ("mit",3)
len(t) evaluates to 3
max((3,5,0)) evaluates 5
t[1] = 4 gives error, can’t modify object
seq = (2,'a',4,(1,2))
index: 0 1 2 3
print(len(seq)) 4
print(seq[3]) (1,2)
print(seq[-1]) (1,2)
print(seq[3][0]) 1
print(seq[4]) error
print(seq[1]) 'a'
print(seq[-2:] (4,(1,2))
print(seq[1:4:2] ('a',(1,2))
print(seq[:-1]) (2,'a',4)
print(seq[1:3]) ('a',4)
for e in seq: 2
print(e) a
4
(1,2)
8
13/12/2024
TUPLES
TUPLES
both = quotient_and_remainder(10,3)
9
13/12/2024
BIG IDEA
Returning
one object (a tuple)
allows you to return
multiple values (tuple elements)
def char_counts(s):
""" s is a string of lowercase chars
Return a tuple where the first element is the
number of vowels in s and the second element
is the number of consonants in s """
10
13/12/2024
VARIABLE NUMBER of
ARGUMENTS
LISTS
11
13/12/2024
LISTS
a_list = []
L = [2, 'a', 4, [1,2]]
[1,2]+[3,4] evaluates to [1,2,3,4]
len(L) evaluates to 4
L[0] evaluates to 2
L[2]+1 evaluates to 5
L[3] evaluates to [1,2], another list!
L[4] gives an error
i = 2
L[i-1] evaluates to 'a' since L[1]='a'
max([3,5,0]) evaluates 5
12
13/12/2024
total = 0 total = 0
for i in range(len(L)): for i in L:
total += L[i] total += i
print(total) print(total)
Notice
• list elements are indexed 0 to len(L)-1
and range(n) goes from 0 to n-1
13
13/12/2024
for e in L: for s in L:
total += e total += len(s)
return(total) return(total)
14
13/12/2024
15
13/12/2024
SUMMARY
16