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:

Python · try it
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 too

List comprehensions: build a list in one line

Python · try it
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:

Python · try it
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

Python · try it
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 done

Step 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]

Python
def first_and_last_three(items):
    return items

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What is "python"[1:4]?

  2. What does items[::-1] do?

Create a free account to track your progress.