List Comprehensions
Learn how to create lists in a single, elegant line of code.
Learning Objectives
- Understand the syntax of List Comprehensions
- Use conditions inside comprehensions
- Learn when to use comprehensions vs. traditional for loops
- Write more 'Pythonic' code
Writing Pythonic Code
In Python, we often want to create a new list by transforming or filtering another list. You could use a for loop for this, but Python offers a more concise and elegant way: List Comprehensions.
Traditional Loop vs. Comprehension
Imagine you want to create a list of square numbers.
Using a For Loop:
old_way.py
|
|
Using a List Comprehension:
new_way.py
|
|
The Syntax
new_list = [expression for item in iterable]
expression: What you want to do to each item.item: The temporary variable name.iterable: The original collection (list, range, etc.).
Adding a Condition (Filtering)
You can also add an if statement to the end to filter items.
filtering.py
|
|
Why use them?
- Shorter: You can do in 1 line what usually takes 3-4.
- Readable: Once you’re used to them, they are very easy to scan.
- Performance: They are slightly faster than manual
.append()calls.
Interactive Practice
Try writing a comprehension that takes a list of strings and creates a new list with all strings converted to uppercase using .upper().
flowchart LR
List[List: 1, 2, 3] --> Comp["[x*2 for x in List]"]
Comp --> Result[New List: 2, 4, 6]
Quiz
Complete this quiz with a minimum score of 80% to mark Day 18 as complete.
Loading quiz...
Discussion
Have questions or want to discuss this lesson? Join the conversation below!