List comprehensions

Python-gereedschapskist

Hugo Bowne-Anderson

Data Scientist at DataCamp

Een lijst vullen met een for-loop

nums = [12, 8, 21, 3, 16]

new_nums = []
for num in nums: new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
Python-gereedschapskist

Een list comprehension

nums = [12, 8, 21, 3, 16]
new_nums = [num + 1 for num in nums]

print(new_nums)
[13, 9, 22, 4, 17]
Python-gereedschapskist

For-loop vs. list comprehension-syntax

new_nums = [num + 1 for num in nums]
for num in nums:
    new_nums.append(num + 1)

print(new_nums)
[13, 9, 22, 4, 17]
Python-gereedschapskist

List comprehension met range()

result = [num for num in range(11)]

print(result)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python-gereedschapskist

List comprehensions

  • Combineer for-loops tot één regel om lijsten te bouwen
  • Onderdelen
    • Iterable
    • Iteratorvariabele (stelt leden van de iterable voor)
    • Uitdrukking voor de output
Python-gereedschapskist

Geneste loops (1)

pairs_1 = []

for num1 in range(0, 2): for num2 in range(6, 8): pairs_1.append((num1, num2))
print(pairs_1)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • Hoe doe je dit met een list comprehension?
Python-gereedschapskist

Geneste loops (2)

pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, 8)]

print(pairs_2)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • Afweging: leesbaarheid
Python-gereedschapskist

Laten we oefenen!

Python-gereedschapskist

Preparing Video For Download...