List Comprehension in Python
Definition:
List comprehension is a concise way to create lists in Python. It allows for the generation of lists
from existing lists or other iterable objects by applying an expression to each element, optionally
filtering the elements using conditions.
Syntax:
new_list = [expression for item in iterable if condition]
● expression: The current item transformed or processed.
● item: The variable representing each element in the iterable.
● iterable: Any Python iterable (like lists, tuples, or strings).
● condition (optional): A filter that determines whether the expression is included in the
new list.
Advantages of List Comprehension:
● Concise and Readable: Reduces the amount of code needed to create a list, making it
easier to read and maintain.
● Performance: List comprehensions are generally faster than traditional for loops for
creating lists.
Examples:
Basic Example:
Create a list of squares for numbers from 0 to 9.
squares = [x ** 2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1.
Using a Condition:
Create a list of even numbers from 0 to 19.
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
2.
Nested List Comprehensions:
Create a list of pairs (i, j) where i is from 0 to 2 and j is from 0 to 2.
pairs = [(i, j) for i in range(3) for j in range(3)]
print(pairs) # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1,
2), (2, 0), (2, 1), (2, 2)]
3.
Transforming Elements:
Convert a list of strings to uppercase.
words = ['hello', 'world', '']
upper_words = [word.upper() for word in words]
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
4.
Conclusion
List comprehensions offer a powerful and elegant way to create and manipulate lists in Python.
By providing a clear and concise syntax, they enhance the readability of the code while
maintaining performance efficiency. Understanding list comprehensions is essential for any
Python programmer looking to write more efficient and Pythonic code.