Python Comprehensions

Python comprehensions are a little complex with how they function and work. Before we get into for loops, it would be an excellent segway to show comprehensions and how they work. Python comprehensions are a quick way to create a list or a dictionary. You need to feed an iterator into the comprehension.  You can iterate over an iterator, like range() in Python.  Range: when you supply a number, it will create a list of numbers you can iterate through.  We will see a few new methods when we are doing comprehension. The two Python methods shown here are:

  • range(start,stop,step)
    • Range will return a range of numbers that can be cast into a list or iterated over based on your input. The valid input into range is:
      • Start:
        • This is the number to start at
      • Stop:
        • up to but not including this number
        • if you use 10, it will stop at 9
      • Step:
        • Like with indexing, you can choose a step size with a range
  • len()
    • This returns the length of the object

List Comprehensions

Let’s say we wanted to create a list and only put the even numbers into the list. Without using a for loop, we can use list comprehensions.  This is done by taking a number and using the modulo operator.  If the result is 0, we are dealing with an even number.

new_list = [x for x in range(0,11,2)]
# Returns
new_list 
[0, 2, 4, 6, 8, 10]

We can also do a nested comprehension.

new_li = [x for x in range(0,11) if x % 2 == 0]
# Returns
new_li 
[0, 2, 4, 6, 8, 10]

If you wanted to square the numbers in a range from 0 to 10:

sq_li = [x ** 2 for x in range(11)]
# Returns
sq_li 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

We can extend this by creating a list where we can have a Celsius to Fahrenheit converter:

cel = [0, 32, 24.5, 36, 10] 
fahrenheit = [((9/5) * temp + 32) for temp in cel]
# Returns
fahrenheit 
[32.0, 89.6, 76.1, 96.8, 50.0]

Dictionary Comprehensions

We can do the same for dictionaries as well. The syntax looks very similar to the list, except we designate the KvP and wrap it in curly braces.

Dictionary with key-value squared:

sq_di = {x:x**2 for x in range(21)}
# Returns
sq_di
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}

What if we only wanted all odd numbers?

sq_odd = {x:x**2 for x in range(21) if x % 2 == 1}
# Returns
sq_odd 
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81, 11: 121, 13: 169, 15: 225, 17: 289, 19: 361}