Python List Comprehensions
List comprehensions provide a concise way to create and transform lists in Python.
They are often faster and more readable than traditional for-loops.
1. Basic Syntax
A list comprehension consists of an expression followed by a for clause inside square brackets.
Python
Basic syntax
[expression for item in iterable]
2. Creating a List
Python
Generate squares of numbers
squares = [x * x for x in range(1, 6)]
print(squares)
Output: [1, 4, 9, 16, 25]
3. Adding Conditions
You can filter elements using an if condition.
Python
Get even numbers only
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
Output: [2, 4, 6, 8, 10]
4. Working with Strings
Python
Convert strings to uppercase
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
print(upper_names)
Output: ['ALICE', 'BOB', 'CHARLIE']
5. Nested List Comprehensions
Python
Flatten a matrix
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)
Output: [1, 2, 3, 4, 5, 6]
6. Using If-Else
Python
Label numbers as even or odd
labels = ['Even' if x % 2 == 0 else 'Odd' for x in range(1, 6)]
print(labels)
Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
7. Why Use List Comprehensions?
1. Cleaner and shorter code.
2. Better readability.
3. Often faster than traditional loops.
4. Widely used in data science and automation.
8. Practice Problems
1. Create a list of cubes from 1 to 20.
2. Extract vowels from a string.
3. Flatten a nested list.
4. Create a list of positive numbers from a mixed list.
Codecrown