List comprehensions

Python Toolbox

Hugo Bowne-Anderson

Data Scientist at DataCamp

Populate a list with a 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 Toolbox

A 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 Toolbox

For loop and 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 Toolbox

List comprehension with range()

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

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

List comprehensions

  • Collapse for loops for building lists into a single line
  • Components
    • Iterable
    • Iterator variable (represent members of iterable)
    • Output expression
Python Toolbox

Nested 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)]
  • How to do this with a list comprehension?
Python Toolbox

Nested 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)]
  • Tradeoff: readability
Python Toolbox

Let's practice!

Python Toolbox

Preparing Video For Download...