Lesson 2 of 7 · 9 min · 2 hands-on steps
Slicing & Comprehensions
Python's superpowers for working with lists and strings in one readable line.
Slicing: take a piece
items[start:stop] gives a new list from start up to (but not including) stop:
letters = ["a", "b", "c", "d", "e"]
print(letters[1:3]) # b, c
print(letters[:2]) # first two
print(letters[-2:]) # last two
print(letters[::-1]) # reversed copy
print("Hello"[1:4]) # works on strings tooList comprehensions: build a list in one line
nums = [1, 2, 3, 4, 5] squares = [n * n for n in nums] evens = [n for n in nums if n % 2 == 0] print(squares) print(evens)
Read it like English: "n times n, for each n in nums." The if at the end filters.
The same thing with a regular loop:
nums = [1, 2, 3, 4, 5]
squares = []
for n in nums:
squares.append(n * n)
print(squares)Comprehensions are shorter, but readability wins. If a comprehension needs a comment to explain it, use a loop.
Dictionary comprehensions
prices = {"apple": 1.2, "pear": 0.8}
with_tax = {fruit: round(p * 1.2, 2) for fruit, p in prices.items()}
print(with_tax)🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · Reverse and slice
Write first_and_last_three(items) that returns a new list: the first 3 items followed by the last 3 items.
first_and_last_three([1,2,3,4,5,6,7,8]) → [1, 2, 3, 6, 7, 8]
def first_and_last_three(items):
return items
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Comprehension
Write passing_names(students) that uses a list comprehension to return the names of students with a score of 70 or more.
def passing_names(students):
return []
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What is "python"[1:4]?
What does items[::-1] do?
Create a free account to track your progress.