Python List Comprehension

The Python list comprehension involves a bracket with the expression and will be executed for each element and the for loop to iterate over each element in the Python list. Read this article to learn more about Python List Comprehension.

What is Python List Comprehension?

The List Comprehension will provide the shorter syntax and will make a new list depending on the values of the existing list.

Example

# Example: Squaring numbers from 1 to 5 using list comprehension
squared_numbers = [x**2 for x in range(1, 6)]

# Output
print(squared_numbers)

Output

[1, 4, 9, 16, 25]

What is Python List Comprehension Syntax?

Syntax: newList = [ expression(element) for element in oldList if condition ] 

Parameter
  • Expression: It will represent the operation that you want to execute on every item within the iterable.
  • element: The term ”variable” will indicate each value taken from the iterable.
  • iterable: it will specify the sequence of the elements that are required to iterate through
  • condition: A filter that will help to decide if the element should be added to the new list.

Return: The Return value of the list comprehension will be referred to as the new list that has the modified elements and will satisfy the given criteria.

List Comprehension in Python Example

The example below shows how to list comprehension to find the square of the number in Python.

# Example: List comprehension to square even numbers from a given list
input_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squared_even_numbers = [x**2 for x in input_numbers if x % 2 == 0]

# Output
print(squared_even_numbers)

Output

[4, 16, 36, 64, 100]

What is the Example of Iteration with List Comprehension

The example provided below illustrates the iteration with the list Comprehension.

# Example: Iterate over a list and add 10 to each element using list comprehension
original_list = [1, 2, 3, 4, 5]

modified_list = [x + 10 for x in original_list]

# Output
print(modified_list)

Output

[11, 12, 13, 14, 15]

What is an example of an Even List Using List Comprehension?

Example

# Example: Create a list of even numbers from 0 to 10 using list comprehension
even_numbers = [x for x in range(11) if x % 2 == 0]

# Output
print(even_numbers)

Output

[0, 2, 4, 6, 8, 10]

What is Matrix using the List Comprehension?

The example provided below will show the matrix using the list comprehension.

# Example: Create a 3x3 matrix and square each element using list comprehension
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

squared_matrix = [[x**2 for x in row] for row in matrix]

# Output
for row in squared_matrix:
    print(row)

Output

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

What is the difference between List Comprehension vs For Loop?

There are several ways to iterate through the list. So, the common way is to use the for loop. Check out the example given below.

# Empty list 
List = [] 
  
# Traditional approach of iterating 
for character in 'Skill  vertex!: 
    List.append(character) 
  
# Display list 
print(List) 

Output

['S' , 'k', 'i', 'l', 'l', 'v', 'e', 'r', 't', 'e', 'x','!']

This example above will show the implementation of the traditional approach inorder to iterate through the list such as list, string, tuple, etc. Thus, the list comprehension will perform the same task and will make the program more simple.

Hence, the list comprehension will translate the traditional iteration approach with the help of a for loop and turn it into a simple formula for easy use. So, the approach given below is used to iterate through the list, string, and tuple with the help of list comprehension in Python.

# Using list comprehension to iterate through loop 
List = [character for character in 'Skillvertex!'] 
  
# Displaying list 
print(List) 

Output

['S', 'k', 'i','l', 'l', 'v', 'e', 'r', 't', 'e', 'x',  '!' ]

What is Time Analysis in List Comprehensions and Loops?

The list comprehension in Python will be more efficient both computationally to the coding space and time than the loop. Hence, they will be written in a single line of code. So, the program given below will show the difference between loops and list comprehension depending on the performance.

import time

# Time analysis for List Comprehension
start_time = time.time()

squared_numbers_comprehension = [x**2 for x in range(1, 10**6)]

end_time = time.time()
comprehension_time = end_time - start_time

# Time analysis for Loop
start_time = time.time()

squared_numbers_loop = []
for x in range(1, 10**6):
    squared_numbers_loop.append(x**2)

end_time = time.time()
loop_time = end_time - start_time

# Output time analysis results
print("List Comprehension Time:", comprehension_time, "seconds")
print("Loop Time:", loop_time, "seconds")

Output

List Comprehension Time: 0.09034180641174316 seconds
Loop Time: 0.1588280200958252 seconds

What is Nested List Comprehension?

The Nested List Comprehension is referred to as the list comprehension within the other list comprehension and works similarly to the nested for loops. The program given below shows the nested loop.

# Example: Nested list comprehension to create a 3x3 matrix with squared elements
matrix_size = 3
squared_matrix = [[x**2 for x in range(row * matrix_size + 1, (row + 1) * matrix_size + 1)] for row in range(matrix_size)]

# Output
for row in squared_matrix:
    print(row)

Output

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

What is List Comprehensions and Lambda

Lambda Expressions are referred to as the shorthand representations of the Python functions. With the help of list comprehensions with lambda, it will make an efficient combination.

# Example: List comprehension with lambda function to square each element
original_list = [1, 2, 3, 4, 5]

squared_list = [(lambda x: x**2)(x) for x in original_list]

# Output
print(squared_list)

Output

[1, 4, 9, 16, 25]

Conditionals in the List Comprehension

This will add the conditions statements to the list comprehension. So, it will make a list using the range, operators, etc, and will apply some conditions to the list with the help of if statements.

What is the Example of Python List Comprehension using the if-else

Check out the example to learn more about Python List Comprehension using the if-else.

Example

# Example: List comprehension with if-else to square even and cube odd numbers
original_list = [1, 2, 3, 4, 5]

modified_list = [x**2 if x % 2 == 0 else x**3 for x in original_list]

# Output
print(modified_list)

Output

[1, 4, 27, 16, 125]

What is the Example of Nested IF with the List Comprehension?

Example

# Example: Nested if in list comprehension to filter even numbers greater than 2
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

filtered_list = [x for x in original_list if x > 2 if x % 2 == 0]

# Output
print(filtered_list)

Output

[4, 6, 8]

Display the square of numbers from 1 to 10

Check out the example below to display the square of numbers from 1 to 10.

Example

# Using a for loop to display the square of numbers from 1 to 10
for num in range(1, 11):
    square = num ** 2
    print(f"The square of {num} is: {square}")

Output

The square of 1 is: 1
The square of 2 is: 4
The square of 3 is: 9
The square of 4 is: 16
The square of 5 is: 25
The square of 6 is: 36
The square of 7 is: 49
The square of 8 is: 64
The square of 9 is: 81
The square of 10 is: 100

What is the Example to Display Transpose of 2D- Matrix?

Example

# Function to calculate the transpose of a matrix
def transpose(matrix):
    # Using zip() to transpose the matrix
    transposed_matrix = [list(row) for row in zip(*matrix)]
    return transposed_matrix

# Example 2D matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Display original matrix
print("Original Matrix:")
for row in matrix:
    print(row)

# Display transpose of the matrix
transposed_matrix = transpose(matrix)
print("\nTransposed Matrix:")
for row in transposed_matrix:
    print(row)

Output

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

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

Toggle the case of each character in the string

Example

# Function to toggle the case of each character in a string
def toggle_case(input_string):
    toggled_string = ''.join([char.lower() if char.isupper() else char.upper() for char in input_string])
    return toggled_string

# Example string
input_string = "Hello World!"

# Display original string
print("Original String:", input_string)

# Toggle the case of each character
toggled_string = toggle_case(input_string)

# Display the result
print("Toggled String:", toggled_string)

Output

Original String: Hello World!
Toggled String: hELLO wORLD!

What is the example to reverse each string in a Tuple?

# Function to reverse each string in a tuple
def reverse_strings_in_tuple(input_tuple):
    reversed_tuple = tuple(s[::-1] for s in input_tuple)
    return reversed_tuple

# Example tuple of strings
original_tuple = ("hello", "world", "python", "code")

# Display original tuple
print("Original Tuple:", original_tuple)

# Reverse each string in the tuple
reversed_tuple = reverse_strings_in_tuple(original_tuple)

# Display the result
print("Reversed Tuple:", reversed_tuple)

Output

Original Tuple: ('hello', 'world', 'python', 'code')
Reversed Tuple: ('olleh', 'dlrow', 'nohtyp', 'edoc')

What is the Example of creating the list of Tuples from the two separate Lists?

Let us look into the example given below to create the two lists of names and ages with the help of zip() in the list comprehension so, it is possible to insert the name and age as the tuple to the list.

Example

# Function to create a list of tuples from two separate lists
def create_tuples(list1, list2):
    tuple_list = list(zip(list1, list2))
    return tuple_list

# Example lists
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']

# Display original lists
print("List 1:", list1)
print("List 2:", list2)

# Create a list of tuples from the two lists
tuple_list = create_tuples(list1, list2)

# Display the result
print("List of Tuples:", tuple_list)

Output

List 1: [1, 2, 3, 4]
List 2: ['a', 'b', 'c', 'd']
List of Tuples: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

What is the Example to display the sum of digits of all the odd elements in the list?

The example provided below has made a list and that will help us to find the digit sum of every odd element in the list.

Example

# Function to calculate the sum of digits in a number
def sum_of_digits(number):
    return sum(int(digit) for digit in str(abs(number)))

# Function to calculate the sum of digits for odd elements in the list
def sum_of_digits_for_odd_elements(input_list):
    odd_elements = [element for element in input_list if element % 2 != 0]
    sum_of_digits_odd = sum(sum_of_digits(element) for element in odd_elements)
    return sum_of_digits_odd

# Example list of numbers
number_list = [123, 45, 678, 91, 234]

# Display original list
print("Original List:", number_list)

# Calculate the sum of digits for odd elements in the list
result = sum_of_digits_for_odd_elements(number_list)

# Display the result
print("Sum of digits for odd elements:", result)

Output

Original List: [123, 45, 678, 91, 234]
Sum of digits for odd elements: 21

Conclusion

In conclusion, Python List Comprehension is a concise and powerful feature that allows for the creation of lists in a more compact and readable manner. It provides a succinct syntax to generate lists, filter elements, and apply expressions in a single line of code. List comprehensions enhance code readability, reduce the need for explicit loops, and contribute to more expressive and Pythonic programming.

Moreover, they are particularly useful for tasks involving iteration, filtering, and transformation of data, making code both efficient and elegant. Overall, Python List Comprehension is a valuable tool for simplifying list-related operations and improving code efficiency.

Python List Comprehension- FAQs

Q1.What is list comprehension in Python?

Ans. The list comprehension is very easy to read, compact, and has an elegant way of forming the list from the existing iterable object.

Q2.What are the 4 types of comprehension in Python?

Ans. List comprehension, dictionary comprehension, set comprehension, and generator comprehension are the 4 types of comprehension in Python.

Q3. What is list comprehension in Python in range?

Ans. It is a concise syntax that is used to create the list from the range or an iterable object by applying the specified object on each of its items.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment