List Comprehension

·

2 min read

List Comprehension

List comprehension is a powerful feature in Python that offers a shorter and more concise syntax for creating new lists based on existing ones.

Here's the general syntax of list comprehension:

[expression for item in iterable if condition]

Let's start with an example using a traditional for loop. We want to generate a list of even numbers within a specified limit:

limit = 20
even_numbers = []
for num in range(1, limit + 1):
    if num % 2 == 0:
        even_numbers.append(num)
print(even_numbers)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Now, let's rewrite the code using List Comprehension, which provides a more concise solution:

limit = 20
even_numbers = [num for num in range(1, limit + 1) if num % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

List comprehensions not only allow you to transform elements but also provide the ability to filter elements based on certain conditions. For example, let's filter out the even numbers from a given list:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]

The resulting list will be [2, 4, 6], containing only the even numbers satisfying the condition num % 2 == 0.

List comprehensions can also be nested, enabling you to create more complex data structures. Let's generate a matrix of zeros with dimensions 3x3:

matrix = [[0 for _ in range(3)] for _ in range(3)]

The resulting matrix will be [[0, 0, 0], [0, 0, 0], [0, 0, 0]], representing a 3x3 matrix filled with zeros.

You can use multiple conditions or ternary expressions within a list comprehension. Here's an example where we create a list with the squares of even numbers and cubes of odd numbers:

numbers = [1, 2, 3, 4, 5, 6]
result = [num ** 2 if num % 2 == 0 else num ** 3 for num in numbers]

The resulting list will be [1, 4, 27, 16, 125, 36], with even numbers squared and odd numbers cubed.

In addition to lists, comprehensions can also be used for dictionaries and sets, providing a concise and efficient way to create these data structures.

In conclusion, mastering list comprehension improves code readability, efficiency, and productivity in Python programming. It simplifies code by combining iteration, conditionals, and expression evaluation into a single line, making your code more concise and expressive.