1
Lesson 1
List comprehension in Python
List comprehension in Python is a quick and elegant way to create new lists by using a single line of code. Instead of writing a longer loop, list comprehension allows you to write what you want in a much simpler and more readable way.
Here’s the structure of a list comprehension:
Basic Structure
Here’s the structure of a list comprehension:
new_list = [expression for item in iterable if condition]
expression : The value you want to put in the new list (can be the item itself or something based on it).for item in iterable : A loop that goes through the items in an iterable (like a list or range).if condition (optional): A filter that decides which items are included.
Examples
1. Create a list of numbers
Instead of writing:
numbers = [] for x in range(5): numbers.append(x)
You can write:
numbers = [x for x in range(5)] print(numbers) # Output: [0, 1, 2, 3, 4]
2. Add a condition
Suppose you only want even numbers:
even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers) # Output: [0, 2, 4, 6, 8]
3. Modify each Item
If you want to square each number:
squared = [x**2 for x in range(5)] print(squared) # Output: [0, 1, 4, 9, 16]
4. With Strings
Make all words uppercase:
words = ["hello", "world"] uppercase_words = [word.upper() for word in words] print(uppercase_words) # Output: ['HELLO', 'WORLD']
Why Use It?
- Conciseness: It makes your code shorter and easier to read.
- Readability: It clearly shows what your list is doing in one line.
- Performance: It's often faster than a regular loop because it’s optimized in Python.
Things to Watch Out For
If the comprehension gets too complex (like having nested loops or too many conditions), it can become hard to read. In those cases, a regular loop might be better!
For example, this might be too much:
result = [x*y for x in range(3) for y in range(3) if x != y]
It’s better to break it into smaller steps if it's confusing.
In short, list comprehension is like a shortcut for creating lists while keeping your code clean and Pythonic!