Containers
List Comprehension practice
First in Line
- Implement promoted, which takes a sequence s and a one-argument function f. It returns a list with the same elements as s, but with all elements e for which f(e) is a true value ordered first. Among those placed first and those placed after, the order stays the same.
- For list comprehensions, a new frame is opened for iterating over the values in a sequence.
1
2
3
4
5
6
7
8
def promoted(s,f):
"""
Return a list with the same elements as s, but with all elements e for which f(e) is a true value placed first
"""
return [elem for elem in s if f(elem)] + [elem for elem in s if not f(elem)]
odd = lambda x: x % 2 == 1
promoted(range(10), odd)
1
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
Strings
- Strings are also considered as sequences.
1
2
3
s = "hello"
print(s[0])
print(list(s))
1
2
h
['h', 'e', 'l', 'l', 'o']
Box-and-Pointer Notation in Environment Diagrams
- Lists are represented as a row of index-labeled adjacent boxes, one per element
- Each box either contains a primitive value or pints to a compound value
Slicing
- We can take a partition and create a copy of said list. Any changes to the copy of the list does not affect the state of the original list.
- If the starting element is creater than the beginning element in list splicing, then an empty list is displayed
1
2
3
4
5
6
7
8
s = [2, 3, 4, 5]
t = s[:]
t[0] = 1
print(s)
t = s
t[0] = 1
print(s)
1
2
[2, 3, 4, 5]
[1, 3, 4, 5]
Implementing double_eights
- Use a list of numbers as our input this time around.
1
2
3
4
5
6
7
8
9
def double_eights(s):
if (s[:2] == [8, 8]):
return True
elif len(s) < 2:
return False
else:
return double_eights(s[1:])
double_eights([2, 8, 4, 6, 8, 2])
1
False
1
all([x > 10 for x in range(20, 30)])
1
True