Python List Exercises for Beginners
Lists are the first data structure most beginners use, and small misunderstandings cause most of the bugs. These exercises focus on indexes, slices, mutation, and the difference between sort and sorted.
Index and slice
The first item is at index 0. A negative index counts from the end. A slice start:stop includes start and excludes stop. If you remember only one rule, remember that the stop index is not included.
orders = ["latte", "mocha", "tea"]
print(orders[0])
print(orders[-1])
print(orders[0:2])Reading a list
Change the list deliberately
append adds one item; remove deletes the first matching value; pop removes by index. These methods change the list in place. A slice creates a new list, so changing the slice does not change the original.
orders = ["latte", "mocha"]
orders.append("tea")
orders.remove("mocha")
print(orders)In-place changes
Sort, total, and avoid the None trap
sort() returns None, so do not assign its result back to the list. sorted() returns a new sorted list. sum and len are useful for quick summaries. Check the result with a print before adding more steps.
prices = [6.0, 4.5, 3.25]
prices.sort()
print(prices)
print(sum(prices))
print(sorted(prices, reverse=True))Sorting and summarising
Exercise: copy before you change
A slice such as prices[:] creates a shallow copy. Use it when you want to sort or edit a working copy while keeping the original order. This is easier to reason about than sorting the only copy and trying to reconstruct the original later.
prices = [6.0, 4.5, 3.25]
original = prices[:]
prices.sort()
print("sorted", prices)
print("original", original)A working copy and the original
Your practice checklist
- Remember that indexing starts at 0.
- The stop index in a slice is excluded.
- append changes the list and returns None.
- Use sorted() when you need to keep the original order.
Common questions
What is the difference between append and extend?
append adds one item, even if that item is a list. extend adds each item from an iterable separately.
Why did my list become None after sorting?
You probably wrote items = items.sort(). sort() changes the list in place and returns None. Call items.sort() by itself, or use items = sorted(items).
How do I get the last item?
Use items[-1]. Negative indexes count from the end, and -1 is the final item.
Practice lists
Twelve list questions covering indexing, slicing, sorting, and totals.
Keep reading: