Advanced comprehensions

Python Toolbox

Hugo Bowne-Anderson

Data Scientist at DataCamp

Conditionals in comprehensions

  • Conditionals on the iterable
    [num ** 2 for num in range(10) if num % 2 == 0]
    
[0, 4, 16, 36, 64]
  • Python documentation on the % operator: The % (modulo) operator yields the remainder from the division of the first argument by the second.
5 % 2
1
6 % 2
0
Python Toolbox

Conditionals in comprehensions

  • Conditionals on the output expression
[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
[0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
Python Toolbox

Dict comprehensions

  • Create dictionaries
  • Use curly braces {} instead of brackets []
pos_neg = {num: -num for num in range(9)}

print(pos_neg)
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8}
print(type(pos_neg))
<class 'dict'>
Python Toolbox

Let's practice!

Python Toolbox

Preparing Video For Download...