Collections
Slicing and comprehensions
Take part of an ordered collection and create a new list with a comprehension.
Lesson 22 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
A slice selects a range from a list or string. The start index is included and the stop index is excluded. Leaving out an end uses the rest of the sequence.
minutes = [10, 20, 30, 40]
print(minutes[1:3])
print(minutes[:2])
print(minutes[2:])[20, 30] [10, 20] [30, 40]
Build a list from another list
A list comprehension creates a new list from an iterable. Start with a clear for loop when the transformation is complex; use a comprehension for a short, readable rule.
minutes = [10, 20, 30, 40]
doubled = [value * 2 for value in minutes]
long_sessions = [value for value in minutes if value >= 25]
print(doubled)
print(long_sessions)[20, 40, 60, 80] [30, 40]
Why this works
A slice returns a new sequence for the requested positions; it does not remove those items from the original list. The stop position is excluded, as it is in range(). A comprehension loops over source values to build a new list and can include a condition to keep only matching values.
Practice
Slice the first three values from a list of five durations. Build a new list containing only durations of at least 20 minutes.
Does minutes[1:3] include the item at index 3?
Reveal answer
No. Slice stop indexes are excluded.
Try another case
For values = [10, 20, 30, 40], what are values[1:3] and [v for v in values if v > 20]?
Check your answer
Reveal answer
They are [20, 30] and [30, 40].
Your progress
Reveal the check answer or reach the end to complete this lesson.