Python list comprehension

List comprehension is a concise and powerful way to create lists using a compact syntax. It allows you to define a new list by iterating over an existing iterable (like lists, tuples, strings, etc.) and applying an expression to each item.

The basic syntax of list comprehension is as follows:

new_list = [expression for item in iterable if condition]
  1. new_list is the name of the new list.
  2. expression is the expression that is evaluated for each item in the iterable.
  3. item is the current item in the iterable.
  4. iterable is the list or iterable that is being used to create the new list.
  5. condition is an optional condition that is used to filter the items in the iterable.

When to use Python list comprehension?

List comprehensions should be used when you need to create a list based on an existing list or iterable. They are especially useful when you need to filter or transform data.

Creating a list of squares using list comprehension

# Using a for loop squares_for_loop = [] for num in range(1, 6): squares_for_loop.append(num ** 2) # Using list comprehension squares_list_comprehension = [num ** 2 for num in range(1, 6)] print(squares_for_loop) # Output: [1, 4, 9, 16, 25] print(squares_list_comprehension) # Output: [1, 4, 9, 16, 25]

Filtering even numbers using list comprehension

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Using a for loop even_numbers_for_loop = [] for num in numbers: if num % 2 == 0: even_numbers_for_loop.append(num) # Using list comprehension even_numbers_list_comprehension = [num for num in numbers if num % 2 == 0] print(even_numbers_for_loop) # Output: [2, 4, 6, 8, 10] print(even_numbers_list_comprehension) # Output: [2, 4, 6, 8, 10]

More examples:

# Create a list of the letters in the word "hello". letters = [x for x in 'hello']
# Create a list of the uppercase letters in the word "hello". uppercase_letters = [x for x in 'hello' if x.isupper()]

Python list comprehension examples

Advantages:

List comprehensions are a powerful way to create lists in Python. They are concise, easy to read, and can be much faster than using a for loop.

Disadvantages:

List comprehensions can be difficult to understand for beginners. They can also be difficult to debug, if there is an error in the expression.

Conclusion

List comprehension allows you to create new lists in a single line of code, making the code more concise and readable. It is a handy technique to filter, transform, or manipulate data in a compact and efficient way, enhancing the productivity and maintainability of your Python code.