Master Python List Comprehension – With Live Examples

Python’s list comprehension is a powerful and concise way to create lists. Providing compact syntax for creating lists in a single line of code, it makes your code more readable and efficient.

Codemagnet has come up with an article, which will help you explore the basics of list comprehension and dive into live examples to help you master this essential Python feature.

What is List Comprehension?

List comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing list (or another iterable). The syntax for list comprehension is [expression for item in iterable if condition], where expression is the output expression, item is the variable representing each item in the iterable, and condition is an optional filter that only includes items for which the condition is true.

Basic List Comprehension Examples:

Lets take some examples and try to understand list comprehension in depth

Creating a list of squares of numbers from 1 to 5:

squares = [x**2 for x in range(1, 6)]
print(squares)

Explanation:

  1. for x in range(1, 6): This part iterates over numbers from 1 to 5 (range(1, 6) generates numbers from 1 to 5, excluding 6) and assigns each number to the variable x.
  2. x**2: This is the expression part of the list comprehension. It calculates the square of x for each iteration.
  3. [x**2 for x in range(1, 6)]: This is the list comprehension syntax, which combines the iteration and expression parts to create a new list containing the squares of numbers from 1 to 5.
  4. squares = [x**2 for x in range(1, 6)]: This assigns the list created by list comprehension to the variable squares.
  5. print(squares): This prints the list of squares [1, 4, 9, 16, 25].

Why is this way efficient to write the code?

Using list comprehension in this way is more efficient and concise compared to traditional approaches using loops because:

  1. Readability: List comprehension makes the code more readable and expressive. It clearly conveys the intent of creating a list of squares in a single line of code.
  2. Compactness: It reduces the amount of code needed to achieve the same result. In this case, it replaces multiple lines of code that would be required for a loop-based approach.
  3. Performance: List comprehension is generally faster than traditional loops in Python because it is optimized for speed. It leverages the underlying Python interpreter’s optimization techniques to perform the operation efficiently.

Filtering even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)

Creating a list of tuples:

fruits = ['apple', 'banana', 'cherry']
fruit_tuples = [(fruit, len(fruit)) for fruit in fruits]
print(fruit_tuples)

Explanation:

  1. fruits = ['apple', 'banana', 'cherry']: This line creates a list called fruits containing three strings: 'apple', 'banana', and 'cherry'.
  2. fruit_tuples = [(fruit, len(fruit)) for fruit in fruits]: This line uses a list comprehension to create a list of tuples called fruit_tuples. The list comprehension iterates over each element in the fruits list (for fruit in fruits) and creates a tuple (fruit, len(fruit)) for each fruit, where len(fruit) is the length of the fruit string. So, for each fruit in the fruits list, a tuple is created containing the fruit itself and its length.
    • (fruit, len(fruit)): This is the expression part of the list comprehension. It creates a tuple with two elements:
      • The first element is the fruit itself, which is the current element in the iteration.
      • The second element is the length of the fruit string, calculated using the len() function.
  3. print(fruit_tuples): This line prints the fruit_tuples list, which contains tuples of fruits and their lengths. The output will be: ['apple', 5), ('banana', 6), ('cherry', 6)].

let’s look at some more advanced examples to demonstrate the flexibility and power of list comprehension:

Advanced List Comprehension Examples:

Flattening a nested list:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = [x for sublist in nested_list for x in sublist]
print(flattened_list)

Explanation:

  1. nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]: This line creates a nested list called nested_list containing three sublists: [1, 2, 3], [4, 5], and [6, 7, 8].
  2. flattened_list = [x for sublist in nested_list for x in sublist]: This line uses nested list comprehension to flatten the nested_list into a single list called flattened_list. The expression [x for sublist in nested_list for x in sublist] iterates over each sublist in nested_list and then iterates over each element x in the sublist. This effectively flattens the nested list structure into a single list.
    • for sublist in nested_list: This is the outer loop that iterates over each sublist in nested_list.
    • for x in sublist: This is the inner loop that iterates over each element x in the current sublist.
  3. print(flattened_list): This line prints the flattened_list, which is the flattened version of the nested_list. The output will be [1, 2, 3, 4, 5, 6, 7, 8].

Using conditional expressions:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
number_types = ['even' if x % 2 == 0 else 'odd' for x in numbers]
print(number_types)

Creating a dictionary from two lists:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary)

Transposing a Matrix:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed)  # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Using Enumerate with List Comprehension:

words = ['apple', 'banana', 'cherry']
indexed_words = [(i, word) for i, word in enumerate(words)]
print(indexed_words)  # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Expalantion:

  1. words = ['apple', 'banana', 'cherry']: This line creates a list named words containing three strings: ‘apple’, ‘banana’, and ‘cherry’.
  2. indexed_words = [(i, word) for i, word in enumerate(words)]: This line uses a list comprehension to create a new list named indexed_words. It iterates over each element in the words list using the enumerate() function, which returns a tuple containing the index (i) and the value (word) of each element. For each element, it creates a tuple (i, word) and adds it to the indexed_words list.
    • enumerate(words) returns an iterable that yields pairs of indices and values from the words list.
    • for i, word in enumerate(words) iterates over each pair, unpacking it into the variables i (index) and word (value).
    • (i, word) creates a tuple containing the index i and the word word.
  3. print(indexed_words): This line prints the indexed_words list to the console.
  4. Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]: This is the output of the print() statement, showing the index-value pairs for each word in the words list. Each tuple represents the index and the corresponding word from the words list.

Using Nested List Comprehension for Matrix Multiplication:

matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
product = [[sum(a*b for a, b in zip(row1, col2)) for col2 in zip(*matrix2)] for row1 in matrix1]
print(product)  # Output: [[19, 22], [43, 50]]

Conclusion:

List comprehension is a powerful feature in Python that allows you to create lists in a concise and readable way. By mastering list comprehension, you can write more efficient and expressive code. We’ve covered the basics of list comprehension and explored various examples to help you understand its usage. Experiment with different examples and use cases to enhance your Python programming skills.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>