Python Fundamentals · Collections
Build a list in one readable line. Compare a loop with its comprehension, then add a filter, and build a dictionary the same way.
nums = [1, 2, 3, 4, 5, 6]
squares = []
for n in nums:
squares.append(n * n)
squares_again = [n * n for n in nums] # the same, in one line
evens = [n for n in nums if n % 2 == 0] # with a filter
labels = {n: "even" if n % 2 == 0 else "odd" for n in nums[:3]}
print(squares == squares_again, evens, labels)nums is created and points to a new list: [1, 2, 3, 4, 5, 6].n is created with the value 1.n changes from 1 to 2.squares points to.n changes from 2 to 3.squares points to.n changes from 3 to 4.squares points to.n changes from 4 to 5.squares points to.n changes from 5 to 6.squares points to.for n in nums.if at the end to keep only some items: the even numbers.