Skip to content
Codewilds

Lesson 14 of 34 · Lists & Tuples

Python Lists: Indexing and Slicing

medium20 XP3 min read

Real programs juggle collections of things: inventory items, high scores, lines of a file. Python's list is the go-to collection — an ordered sequence of values that can grow, shrink and change. In this lesson you'll create lists, read items by position, and master slicing, one of Python's most elegant features.

Creating lists

Write a list with square brackets and commas. Lists can hold any type, even a mix:

heroes = ["Ada", "Bo", "Cy"]
scores = [98, 75, 88]
mixed = ["potion", 3, True, None]
empty = []

print(len(heroes))          # 3
print(list(range(5)))       # [0, 1, 2, 3, 4]
print(list("hiss"))         # ['h', 'i', 's', 's']

Indexing: getting one item

Every item has an index, starting at 0. Negative indexes count from the end, so -1 is always the last item:

heroes = ["Ada", "Bo", "Cy"]
print(heroes[0])    # Ada
print(heroes[2])    # Cy
print(heroes[-1])   # Cy
print(heroes[-2])   # Bo
print(heroes[3])    # IndexError: list index out of range

The last valid index is len(heroes) - 1.

Lists are mutable

Unlike strings, lists can be changed in place. Assign to an index to replace an item, and use in to check membership:

heroes[1] = "Bea"
print(heroes)            # ['Ada', 'Bea', 'Cy']
print("Cy" in heroes)    # True

for hero in heroes:
    print(f"{hero} joins the party")

The next lesson covers list methods such as append() for adding items.

Slicing: getting part of a list

A slice items[start:stop] returns a new list with the items from start up to — but not including — stop. Leave out start to begin at the front, or stop to run to the end:

nums = [10, 20, 30, 40, 50]
print(nums[1:4])    # [20, 30, 40]
print(nums[:2])     # [10, 20]       first two
print(nums[2:])     # [30, 40, 50]   from index 2 on
print(nums[-2:])    # [40, 50]       last two
print(nums[1:-1])   # [20, 30, 40]   all but the ends

An optional third value is the step:

print(nums[::2])    # [10, 30, 50]   every second item
print(nums[::-1])   # [50, 40, 30, 20, 10]   reversed

Slices are forgiving: indexes beyond the ends are clamped instead of raising errors, so nums[3:100] is [40, 50] and nums[10:] is []. Strings slice exactly the same way: "serpent"[:3] is "ser".

Copies versus aliases

Assigning a list to another variable does not copy it — both names point to the same list:

original = [1, 2, 3]
alias = original
alias[0] = 99
print(original)       # [99, 2, 3]  <- changed too!

copy = original[:]    # a slice creates a new list
copy[0] = 1
print(original)       # [99, 2, 3]  <- untouched

Functions that receive a list should usually return a new list rather than quietly modifying the caller's data.

Common mistakes

  • Off-by-one slices: the stop index is excluded; nums[0:3] has three items, not four.
  • Indexing past the end: nums[len(nums)] raises IndexError — but the same index in a slice doesn't.
  • The -0 trap: nums[-n:] gives the last n items… except when n is 0, because -0 is just 0 and nums[0:] is the whole list.
  • Accidental aliasing: b = a shares one list; use a[:] (or list(a)) when you need a copy.

Assignment

Write three functions. Each must return a new list and leave the input unchanged:

  1. swap_ends(items) returns a copy with the first and last items swapped. Lists with fewer than two items come back as an unchanged copy.
  2. last_n(items, n) returns the last n items. If n is 0, return []; if n is larger than the list, return a copy of the whole list.
  3. rotate_left(items, k) returns the list rotated left by k positions, so the first k items move to the end. k may be larger than the list (wrap around); an empty list returns [].
swap_ends([1, 2, 3, 4])          # [4, 2, 3, 1]
last_n([1, 2, 3, 4, 5], 2)       # [4, 5]
last_n([1, 2, 3], 0)             # []
rotate_left([1, 2, 3, 4, 5], 2)  # [3, 4, 5, 1, 2]
rotate_left([1, 2, 3], 4)        # [2, 3, 1]

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Arrays and lists in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 14 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.