List Comprehensions

Self Learning

Objectives Of This Post

This post is the first in what I intend to be a series of posts on programming in Python. I put together a fair bit of Python code for my job in my role as an analyst. But most of that code is merely gluing together snippets from the internet, as my main focus isn’t writing software but merely accomplishing a task. In this series, I hope to explain concepts with the idea that teaching the material will help me learn it better.

List Comprehensions Explained Simply

Replacing a For Loop

One interesting feature in Python is List Comprehensions. List Comprehensions allow you to take a for loop and express it as a single line of code.

For instance, this loop will iterate through a dictionary, returning the keys and add them to a list.

dunphy_family = {'Phil':'Parent', 'Claire':'Parent', 'Haley':'Child', 'Alex':'Child', 'Luke':'Child'}

dunphy_names = [] # Initialize List

for name in dunphy_family:
    dunphy_names.append(name)
    
print(dunphy_names)

['Phil', 'Claire', 'Haley', 'Alex', 'Luke']

This output can be obtained using a list comprehension, which results in replacing three lines of this code with one.

dunphy_family = {'Phil':'Parent', 'Claire':'Parent', 'Haley':'Child', 'Alex':'Child', 'Luke':'Child'}

dunphy_names = [name for name in dunphy_family]
    
print(dunphy_names)


['Phil', 'Claire', 'Haley', 'Alex', 'Luke']
Filtering

We can take things one step further by using List Comprehensions to filter the input before creating the output. For instance, if we wanted to see a list of just the Dunphy children, we might do this in a loop.

dunphy_family = {'Phil':'Parent', 'Claire':'Parent', 'Haley':'Child', 'Alex':'Child', 'Luke':'Child'}

dunphy_names = [] # Initialize List

for name, role in dunphy_family.items():
    if role == "Child":
        dunphy_names.append(name)
    
print(dunphy_names)

['Haley', 'Alex', 'Luke']

But with List Comprehensions, we can replace four lines of code with a single line.

dunphy_family = {'Phil':'Parent', 'Claire':'Parent', 'Haley':'Child', 'Alex':'Child', 'Luke':'Child'}

dunphy_names = [name for name, role in dunphy_family.items() if role == "Child"] 
    
print(dunphy_names)

['Haley', 'Alex', 'Luke']
Conclusion

I see List Comprehensions as a way to accomplish a couple of goals:

  • Improve the Readability of the code
  • Save a little time writing code

Plus they are kind of cool!