Advanced Python - 3. List Comprehension
3.2 The "Long Way" (What We Already Know)
3.3 The "Short Way" (Introducing List Comprehension)
3.4 Adding a Condition (The if Statement)
3. List Comprehension
3.1 Introduction
- This is a concept that uses our knowledge of lists, loops, and conditional statements (if/else). We know how to build lists, add things to them and go through them item by item. Today, we are going to learn a way to combine all of these ideas into one very efficient line of code.
- Benefits of List Comprehension:
- Readability: Once the concept is understood, these single lines of code are often much easier to read and understand than a longer loop. They clearly state 'make a list by doing X for Y if Z'."
- Conciseness: Less lines of code means less chance for typos and faster coding.
- Performance: Python can often build these lists faster using list comprehensions than it can with a traditional for loop and append.
- It's a "Pythonic" Way: Experienced Python programmers use list comprehensions all the time. Learning this makes your code look more like professional Python code.
3.2 The "Long Way" (What We Already Know)
- An example of the way we have been doing it: Imagine we have a list of numbers, and we want to create a new list where each number is doubled.
# Our original list of numbers
original_numbers = [1, 2, 3, 4, 5]
# An empty list to store our doubled numbers
doubled_numbers = []
# Now, we use a loop to go through each number and double it
for number in original_numbers:
new_number = number * 2
doubled_numbers.append(new_number)
print("Original Numbers:", original_numbers)
print("Doubled Numbers:", doubled_numbers)
(check the print statements. Make sure to change or explain how they work)
OUTPUT: Original Numbers: [1, 2, 3, 4, 5]
Doubled Numbers: [2, 4, 6, 8, 10]
3.3 The "Short Way" (Introducing List Comprehension)
- Python has a way to do exactly the same thing, but in just one line. This is where list comprehension comes in.
- List comprehension allows us to say:
Make me a new list where you do THIS action for every item IN this other list
# Our original list of numbers (same as before)
original_numbers = [1, 2, 3, 4, 5]
# *** List Comprehension! ***
doubled_numbers_comp = [number * 2 for number in original_numbers]
print("Doubled Numbers (the short way!):", doubled_numbers_comp)
OUTPUT: Doubled Numbers (the short way!): [2, 4, 6, 8, 10]
Explanation:
- [ ]: This tells Python “I'm building a new list”
- number * 2: This is the expression. It's the 'what to do' part. For each item, we want to multiply it by 2. This is the new item that will go into our new list.
- for number in original_numbers: This is just like the for loop you already know. It says “Go through each number (that's our temporary variable) in the original_numbers list”
- Overall, this line says: “Create a new list by taking each number from original_numbers and multiply that number by 2'."
3.4 Adding a Condition (The if Statement)
- What if we only want to double the even numbers? In the 'long way,' we'd use an if statement inside our loop.
The “long way”:
# Our original list of numbers (same as before)
original_numbers = [1, 2, 3, 4, 5]
# The long way with a condition
even_doubled_long = []
for number in original_numbers:
if number % 2 == 0: # Check if the number is even
even_doubled_long.append(number * 2)
print("\nEven Doubled Numbers (the long way):", even_doubled_long)
OUTPUT: Even Doubled Numbers (the long way): [4, 8]
With List Comprehension, we can just add that if statement right into our one line!:
# Our original list of numbers (same as before)
original_numbers = [1, 2, 3, 4, 5]
# *** List Comprehension! ***
even_doubled_comp = [number * 2 for number in original_numbers if number % 2 == 0]
print("Even Doubled Numbers (the short way!):", even_doubled_comp)
OUTPUT: Even Doubled Numbers (the short way!): [4, 8]
Explanation:
- We just tacked on if number % 2 == 0 at the end of our one line.
- It reads almost like a sentence: 'Create a new list by taking each number from original_numbers, multiplying it by 2, if that number is even.' How neat is that?"
Chapter 3 Assignments
A3.1 Perfect Squares
- Create a list of the first 10 perfect squares using list comprehension and the range function. The final list should look like this:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
A3.2 Celsius Farenheit
- Given a list of temperatures in Celsius: [-5, 0, 10, 20, 30, 40], create a new list of temperatures in Fahrenheit. The conversion formula is
Fahrenheit = Celsius * 1.8 + 32
A3.3 Perfect Squares
- From the list of words: ['apple', 'banana', 'kiwi', 'grape', 'orange'], create a new list containing only the words that have 5 letters or more. This will need a conditional.