curriculum/challenges/english/blocks/lecture-working-with-loops-and-sequences/6839e4d62ae09d1661e4cf9b.md
For the past few lessons, you have been getting comfortable working with loops like this:
even_numbers = []
for num in range(21):
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
This example creates a new empty list called even_numbers and loops through a sequence of numbers between 0 and 20. Inside the loop, there's a condition that checks if the current number has a remainder of 0 when divided by 2. This is used to determine if the number is even. If the condition is True, then the current num is appended at the end of the even_numbers list. Finally, we print the even_numbers list to the console.
While this code works, there is a more concise way to write this that uses list comprehension instead. List comprehension allows you to create a new list in a single line by combining a loop and condition directly within square brackets. This makes the code shorter and often easier to read.
Here is the refactored example from earlier using square brackets:
even_numbers = [num for num in range(21) if num % 2 == 0]
print(even_numbers)
In this refactored example, the even_numbers list is created using a single line of code. The list comprehension loops through numbers from 0 to 20, and includes only those that are divisible by 2. This approach is more compact and eliminates the need for a separate loop and conditional block.
Let's take a look at another example so we can better understand how list comprehension works:
numbers = [1, 2, 3, 4, 5]
result = [(num, 'Even') if num % 2 == 0 else (num, 'Odd') for num in numbers]
print(result)
In this example, we have a list of numbers and want to create a new list of tuples indicating which numbers are even or odd. In the first part of the list comprehension, we use an if statement to check if the number is evenly divisible by 2. If so, then the result is a tuple of that number followed by the word Even. Otherwise, the result is a tuple with the number followed by the word Odd.
Here is what the result looks like printed in the console:
[(1, 'Odd'), (2, 'Even'), (3, 'Odd'), (4, 'Even'), (5, 'Odd')]
Another way to create a list starting from an existing iterable is the filter() function. Here is an example of creating a new list of just words longer than four characters:
words = ['tree', 'sky', 'mountain', 'river', 'cloud', 'sun']
def is_long_word(word):
return len(word) > 4
long_words = list(filter(is_long_word, words))
print(long_words) # ['mountain', 'river', 'cloud']
The filter() function is used to select elements from an iterable that meet a specific condition. The filter() function accepts a function and an iterable for its arguments. In this example, we are passing in an is_long_word function into the filter() function to check if the current word count is greater than 4. All words that have a character count greater than 4 are added into a new list and assigned to the long_words variable.
Aside from the filter() function, there are a few more functions that are helpful when working with lists. Another function to be aware of is the map() function, which takes an iterable and applies a function to each of its elements. Here is an example of using the map() function to convert a list of temperatures from Celsius to Fahrenheit:
celsius = [0, 10, 20, 30, 40]
def to_fahrenheit(temp):
return (temp * 9/5) + 32
fahrenheit = list(map(to_fahrenheit, celsius))
print(fahrenheit) # [32.0, 50.0, 68.0, 86.0, 104.0]
Just like the filter() function, map() accepts a function and an iterable for its arguments. The to_fahrenheit function takes a temperature and converts it from Celsius to Fahrenheit.
The last function we will look at is the sum() function. This function is used to get the sum from an iterable like a list or tuple. Here is an example of using the sum() function:
numbers = [5, 10, 15, 20]
total = sum(numbers)
print(total) # Result: 50
You can also pass in an optional start argument which sets the initial value for the summation. Here is an updated example using the start argument as a positional argument:
numbers = [5, 10, 15, 20]
total = sum(numbers, 10) # positional argument
print(total) # 60
You can also choose to use the start argument as a keyword argument like this instead:
numbers = [5, 10, 15, 20]
total = sum(numbers, start=10) # keyword argument
print(total) # 60
Both versions will produce the same result, but the keyword argument is a little more explicit.
List comprehension as well as other functions like map(), filter(), and sum() might seem a little confusing at first. But with enough practice and time, you will start to feel more comfortable using them in your Python programs.
Which of the following is the correct way to use list comprehension?
[while for loop num in range(21)]
Review the beginning of the lesson for the answer.
[num for num in range(21) if num % 2 == 0]
[num for num]
Review the beginning of the lesson for the answer.
[for num in range(21) if num % 2 == 0]
Review the beginning of the lesson for the answer.
2
Which of the following functions takes an iterable and applies a function to each of its elements?
memoryview
Think of the function that "maps" a transformation onto every item in a list, one by one.
map
max
Think of the function that "maps" a transformation onto every item in a list, one by one.
min
Think of the function that "maps" a transformation onto every item in a list, one by one.
2
What will be printed to the console?
numbers = [5, 10, 15, 20]
total = sum(numbers, start=10)
print(total) # ?
60
50
Review the end of the lesson for the answer.
40
Review the end of the lesson for the answer.
70
Review the end of the lesson for the answer.
1