w3resource

Python List Comprehensions: For Concise and Readable Code

Introduction to Python List Comprehension

List comprehensions in Python provide a concise way to create lists. They are not only more readable but also more efficient than traditional for-loops. This tutorial focuses on practical examples to help you master list comprehensions with minimal theory.

Basic List Comprehension:

A basic list comprehension is a compact way to create a list by applying an expression to each item in an iterable.

Example 1: Creating a list of squares

This example shows how to create a list of squares using list comprehension.

Code:

# Create a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]

# Print the list of squares
print(squares) 

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Explanation:

The expression 'x**2' is applied to each element 'x' in the range from 0 to 9. The result is a list of squares of these numbers. This single line of code replaces what would typically require multiple lines using a for-loop.

Filtering with list comprehensions:

List comprehensions can include an if condition to filter items from the iterable.

Example 2: Filtering Even Numbers

This example demonstrates how to filter even numbers using a list comprehension.

Code:

# Create a list of even numbers from 0 to 9
evens = [x for x in range(10) if x % 2 == 0]

# Print the list of even numbers
print(evens)

Output:

[0, 2, 4, 6, 8]

Explanation:

The list comprehension iterates through numbers from 0 to 9 and includes only those numbers that satisfy the condition 'x % 2 == 0' (i.e., even numbers). The result is a concise list of even numbers.

List Comprehensions with nested loops:

List comprehensions can also be used with nested loops to generate lists from combinations of items.

Example 3: Creating a List of Pairs

This example shows how to create a list of coordinate pairs using nested loops in a list comprehension.

Code:

# Create a list of coordinate pairs (x, y) for x and y in range(3)
pairs = [(x, y) for x in range(3) for y in range(3)]

# Print the list of pairs
print(pairs)

Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Explanation:

The list comprehension uses two nested loops: one iterating over 'x' and the other over 'y', both ranging from 0 to 2. The result is a list of all possible pairs '(x, y)' formed by the two loops.

Flattening a nested list:

List comprehensions can be used to flatten nested lists into a single list.

Example 4: Flattening a 2D List

This example demonstrates how to flatten a 2D list into a 1D list using list comprehension.

Code:

# A 2D list (list of lists)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Flatten the 2D list into a 1D list
flattened = [num for row in matrix for num in row]

# Print the flattened list
print(flattened)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

The list comprehension iterates over each 'row' in the 'matrix', and then iterates over each 'num' in that 'row', adding each number to the 'flattened' list. The result is a single list containing all elements from the original nested list.

Conditional expressions in list comprehensions:

You can include a conditional expression to choose different values based on a condition.

Example 5: Replacing Negative Numbers with Zero

This example shows how to replace negative numbers in a list with zero using a conditional expression in a list comprehension.

Code:

# List with mixed positive and negative numbers
numbers = [-15, 13, -12, 17, -11, 0, 14]

# Replace negative numbers with zero
non_negative = [x if x >= 0 else 0 for x in numbers]

# Print the new list
print(non_negative)

Output:

[0, 13, 0, 17, 0, 0, 14]

Explanation:

The list comprehension iterates over 'numbers' and checks if each number 'x' is non-negative ('x >= 0'). If the condition is met, 'x' is added to the new list; otherwise, '0' is added. This results in a list where all negative numbers are replaced by zero.

Using List Comprehensions with Functions:

List comprehensions can apply functions to items in an iterable to generate a new list.

Example 6: Applying a function to each element

This example demonstrates how to apply a function to each element in a list using a list comprehension.

Code:

# Define a function that squares a number
def square(x):
    return x**2

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Apply the square function to each element in the list
squared_numbers = [square(x) for x in numbers]

# Print the list of squared numbers
print(squared_numbers)

Output:

[1, 4, 9, 16, 25]

Explanation:

The list comprehension iterates over the 'numbers' list and applies the 'square' function to each element 'x'. The result is a new list containing the squares of the original numbers.

List Comprehension with Dictionaries:

List comprehensions can be used to generate dictionaries by pairing keys with values.

Example 7: Creating a Dictionary from two lists

This example shows how to create a dictionary from two lists using a list comprehension.

Code:

# Two lists: one of keys and one of values
keys = ['x', 'y', 'z']
values = [1, 2, 3]

# Create a dictionary using list comprehension
dictionary = {k: v for k, v in zip(keys, values)}

# Print the dictionary
print(dictionary)

Output:

{'x': 1, 'y': 2, 'z': 3}

Explanation:

The 'zip(keys, values)' function pairs elements from the 'keys' and 'values' lists. The list comprehension then iterates over these pairs and creates key-value pairs in the 'dictionary'.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python/python-list-comprehension-with-examples.php