Lesson 7 of 33
In Progress

List Comprehensions

Yasin Cakal

List comprehensions are a concise and efficient way to create new lists from existing iterable objects, such as strings, lists, and tuples. They are a powerful feature of Python that allows you to write concise and expressive code to manipulate and process data.

To create a list comprehension, you start with a list of elements, followed by a for loop that iterates over the elements, and an expression that specifies how to transform the elements. The result is a new list that contains the transformed elements. Here’s an example:

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use a list comprehension to double each number
doubles = [n * 2 for n in numbers]

print(doubles)  # Output: [2, 4, 6, 8, 10]


You can also add a condition to the list comprehension to filter the elements. The condition is added after the for loop and before the expression. For example:

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use a list comprehension to double only the even numbers
even_doubles = [n * 2 for n in numbers if n % 2 == 0]

print(even_doubles)  # Output: [4, 8]


List comprehensions are particularly useful when you need to perform a transformation on a large dataset, or when you need to perform a complex transformation that would be difficult to do with a traditional for loop. For example, let’s say you have a list of strings and you want to create a new list that contains only the strings that are palindromes (words that are spelled the same backwards and forwards). You can use a list comprehension to do this in a single line of code:

# Create a list of strings
words = ['racecar', 'hello', 'world', 'madam', 'level']

# Use a list comprehension to find the palindromes
palindromes = [w for w in words if w == w[::-1]]

print(palindromes)  # Output: ['racecar', 'madam', 'level']


List comprehensions are also useful when you need to create a list of tuples, or when you need to flatten a list of lists. For example:

# Create a list of tuples
tuples = [(1, 2), (3, 4), (5, 6)]

# Use a list comprehension to unpack the tuples and create a flat list
flat_list = [x for t in tuples for x in t]

print(flat_list)  # Output: [1, 2, 3, 4, 5, 6]

# Create a list of lists
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Use a list comprehension to flatten the list
flat_list = [x for sublist in lists for x in sublist]

print(flat_list)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]


Conclusion

In summary, list comprehensions are a concise and efficient way to create new lists from existing iterable objects in Python. They allow you to write expressive and readable code to transform and manipulate data, and can be used to perform complex transformations with a single line of code. By mastering list comprehensions, you’ll be able to write more efficient and effective Python programs.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a list comprehension that takes a list of numbers as input and returns a new list that contains the squares of the numbers.

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use a list comprehension to square the numbers
squares = [n ** 2 for n in numbers]

print(squares)  # Output: [1, 4, 9, 16, 25]


Write a list comprehension that takes a list of words as input and returns a new list that contains only the words that are palindromes.

# Create a list of words
words = ['racecar', 'hello', 'world', 'madam', 'level']

# Use a list comprehension to find the palindromes
palindromes = [w for w in words if w == w[::-1]]

print(palindromes)  # Output: ['racecar', 'madam', 'level']


Write a list comprehension that takes a list of tuples as input and returns a new list that contains only the second element of each tuple.

# Create a list of tuples
tuples = [(1, 2), (3, 4), (5, 6)]

# Use a list comprehension to unpack the tuples and create a list of the second element of each tuple
second_elements = [x[1] for x in tuples]

print(second_elements)  # Output: [2, 4, 6]


Write a list comprehension that takes a list of lists as input and returns a new list that contains the elements of the inner lists concatenated into strings.

# Create a list of lists
lists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

# Use a list comprehension to concatenate the elements of the inner lists into strings
strings = [' '.join(x) for x in lists]

print(strings)  # Output: ['a b c', 'd e f', 'g h i']


Write a list comprehension that takes a list of numbers as input and returns a new list that contains only the numbers that are divisible by 3.

# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use a list comprehension to find the numbers that are divisible by 3
divisible_by_three = [n for n in numbers if n % 3 == 0]

print(divisible_by_three)  # Output: [3, 6, 9]