Advanced List Operations: Comprehensions, Mapping, and Reducing

This example will demonstrate some advanced list operations including list comprehensions, nested lists, and using higher-order functions like map(), filter(), and reduce() from the functools module.

Code Example

from functools import reduce

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

# 1. List Comprehension: Create a new list with the squares of the numbers
squares = [x**2 for x in numbers]

# 2. Nested List Comprehension: Create a 3x3 matrix filled with zeros
matrix = [[0 for _ in range(3)] for _ in range(3)]

# 3. Using map() to create a list of cube of numbers
cubes = list(map(lambda x: x**3, numbers))

# 4. Using filter() to create a list of even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# 5. Using reduce() to calculate the product of all numbers in the list
product = reduce(lambda x, y: x * y, numbers)

# Print the results
print("Original numbers:", numbers)
print("Squares:", squares)
print("Matrix:", matrix)
print("Cubes:", cubes)
print("Even numbers:", even_numbers)
print("Product of all numbers:", product)

Code Explanation

List Comprehension

squares = [x**2 for x in numbers]

This creates a new list squares where each element is the square of the corresponding element in numbers.

Nested List Comprehension

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

This generates a 3×3 matrix (a list of lists) filled with zeros. The inner list comprehension [0 for _ in range(3)] creates a row of three zeros, and the outer list comprehension replicates this row three times.

Using map() Function

cubes = list(map(lambda x: x**3, numbers))

The map() function applies the lambda function lambda x: x**3 to each element in numbers, producing a list of their cubes.

Using filter() Function

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

The filter() function filters out elements in numbers that do not satisfy the condition x % 2 == 0 (i.e., it keeps only even numbers).

Using reduce() Function

product = reduce(lambda x, y: x * y, numbers)

The reduce() function applies the lambda function lambda x, y: x * y cumulatively to the items of numbers, from left to right, to reduce the list to a single value representing the product of all elements.

Output

Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Matrix: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Cubes: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Even numbers: [2, 4, 6, 8, 10]
Product of all numbers: 3628800