Lesson 14 of 34 · Lists & Tuples
Python Lists: Indexing and Slicing
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
stopindex is excluded;nums[0:3]has three items, not four. - Indexing past the end:
nums[len(nums)]raisesIndexError— but the same index in a slice doesn't. - The
-0trap:nums[-n:]gives the lastnitems… except whennis0, because-0is just0andnums[0:]is the whole list. - Accidental aliasing:
b = ashares one list; usea[:](orlist(a)) when you need a copy.
Assignment
Write three functions. Each must return a new list and leave the input unchanged:
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.last_n(items, n)returns the lastnitems. Ifnis0, return[]; ifnis larger than the list, return a copy of the whole list.rotate_left(items, k)returns the list rotated left bykpositions, so the firstkitems move to the end.kmay 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
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
- JavaScript Arrays: Methods and Loops for Beginners · JavaScript
- Go Arrays vs Slices: Slicing and range · Go
- Java Arrays and the for-each Loop · Java
- C# Arrays and the foreach Loop · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .