Lists: Conceptual Solutions
LIST COMPREHENSIONS AND LIST SLICING
Write out the list each list comprehension creates.
lst = [1, 2, 3, 4, 5, 6, 7, 8]
[x + 1 for x in lst]
[2, 3, 4, 5, 6, 7, 8, 9]
[x // 2 for x in lst if x % 2 == 0]
[1, 2, 3, 4]
[[y + 1 for y in range(x)] for x in lst if x < 4]
[[1], [1, 2], [1, 2, 3]]
Write out each sliced list.
lst = [1, 2, 3, 4, 5, 6, 7, 8]
lst[0 : 4]
[1, 2, 3, 4]
lst[: 8 : 2]
[1, 3, 5, 7]
lst[1 : -2 : -1]
[6, 5, 4, 3, 2, 1]
LIST FUNCTIONS
Draw out lst1 and lst2 each step of the way.
lst1 = [1, 2, 3, 4]
lst2 = [5, 6, 7, 8]
lst2.append(lst1.pop())
lst1.extend([9, 10])
lst2.append([11, 12])
lst1.pop(lst2[lst2[0] - 1])
lst2.remove(lst1[0] + 4)
code writing
Write a function that will take in a number n and create a list of all multiples of 3 from 0 to n inclusive. Assume n will always be >= 0.
def n_list(n):
>>> n_list(3)
[0, 3]
>>> n_list(6)
[0, 3, 6]
return [x for x in range(n + 1) if x % 3 == 0]