Program 1
List comprehension
Squares from 1 to 10.
python
squares = [x ** 2 for x in range(1, 11)]
print(squares)Topic 14 of 17
Build lists, sets, and dicts in one expressive line.
Program 1
Squares from 1 to 10.
squares = [x ** 2 for x in range(1, 11)]
print(squares)Program 1
Filter while building.
nums = range(1, 21)
div_3_or_5 = [n for n in nums if n % 3 == 0 or n % 5 == 0]
print(div_3_or_5)Program 2
Construct dicts and sets concisely.
chars = "mississippi"
count = {c: chars.count(c) for c in set(chars)}
print(count)Program 1
Flatten a 2-D list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row]
print(flat)