w3resource

What are Python list comprehensions? Explain the syntax and example of a list comprehension.

Python list comprehensions: Syntax and examples

Python list comprehensions are a way to create new lists using compact and readable syntax. They allow us to apply an expression to each element of an existing list and optionally filter elements based on certain conditions.

Syntax:

new_c_list = [expression for item in original_list if condition]
  • new_c_list: The new list that will be created.
  • expression: The operation or transformation to be applied to each item in the iterable.
  • item: A variable that represents each element in the original list during iteration.
  • original_list: The existing list from which elements will be processed.
  • if condition (optional): A condition that filters elements based on a specific condition. The expression is only applied to items that satisfy the condition.

Example-1: Creating a list of cubes of numbers

Code:

# Using a traditional loop
numbers = [1, 2, 3, 4, 5]
cubes = []
for num in numbers:
    cubes.append(num ** 3)
print("Using a traditional loop:")
print(cubes)  
# Using a list comprehension
cubes = [1, 2, 3, 4, 5]
cubes = [num ** 3 for num in numbers]
print("\nUsing a list comprehension:")
print(cubes)  

Output:

Using a traditional loop:
[1, 8, 27, 64, 125]

Using a list comprehension:
[1, 8, 27, 64, 125]

In the above example, we create a list of cubes of numbers using both a traditional loop and list comprehension. The list comprehension [num ** 3 for num in numbers] generates the same result as the loop, but in a more concise and readable form.

Example-2: Filtering odd numbers from a list

Code:

# Using a traditional loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
even_numbers = []
for num in numbers:
    if num % 2 != 0:
        even_numbers.append(num)
print("Using a traditional loop:")
print(even_numbers)
# Using a list comprehension with a condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
even_numbers = [num for num in numbers if num % 2 != 0]
print("\nUsing a list comprehension with a condition:")
print(even_numbers)

Output:

Using a traditional loop:
[1, 3, 5, 7, 9, 11]

Using a list comprehension with a condition:
[1, 3, 5, 7, 9, 11]


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://www.w3resource.com/python-interview/what-are-python-list-comprehensions-explain-the-syntax-and-example-of-a-list-comprehension.php