Bonus material: List comprehensions

Materials by: John Blischak and other Software Carpentry instructors (Joshua R. Smith, Milad Fatenejad, Katy Huff, Tommy Guy and many more)

Note - this stuff confuses most people. If you are feeling confident, please proceed! Otherwise, this is really "bonus" material, so please focus on the core material.

Introducing comprehensions

Python has another way to perform iteration called list comprehensions. First, let's look at how we would create a "transformed" version of a list with loops. (If you don't understand loops already, you should probably review that material!)


In [ ]:
# Multiply every number in a list by 2 using a for loop
nums1 = [5, 1, 3, 10]
nums2 = []
for i in range(len(nums1)):
    nums2.append(nums1[i] * 2)
    
print nums2

You can see that doing the same thing with a list comprehension is very clear and compact (as long as it makes sense ;)


In [ ]:
# Multiply every number in a list by 2 using a list comprehension
nums2 = [x * 2 for x in nums1]

print nums2

What if we also have some conditional logic?


In [ ]:
# Multiply every number in a list by 2, but only if the number is greater than 4
nums1 = [5, 1, 3, 10]
nums2 = []
for i in range(len(nums1)):
    if nums1[i] > 4:
        nums2.append(nums1[i] * 2)
    
print nums2

In [ ]:
# And using a list comprehension
nums2 = [x * 2 for x in nums1 if x > 4]

print nums2

Repeated Exercise: Convert genotypes

This is the same material from 08-Loops. See if you can use list comprehensions to do the following exercises with more compact code.

Again, create a new list which has the converted genotype for each subject ('AA' -> 0, 'AG' -> 1, 'GG' -> 2). Use the Dictionary provided below as a lookup table to do the conversion.


In [ ]:
converted = {'AA': 0, 'AG': 1, 'GG': 2}

genos = ['AA', 'GG', 'AG', 'AG', 'GG']
genos_new = [] # Use a comprehension here

Check your work:


In [ ]:
genos_new == [0, 2, 1, 1, 2]