Lists
Create, slice, modify and sort lists, key functions, unpacking, shallow vs deep copies and common traps.
The list is Python's workhorse collection: an ordered, changeable sequence of values. Shopping carts, rows from a database, lines from a file, search results — they're all lists. This lesson covers creating, reading, changing, sorting and copying lists, plus the pitfalls that catch everyone at least once.
Creating lists#
Indexing and slicing#
Lists use the same indexing and slicing rules as strings — zero-based, negative from the end, stop index excluded:
Unlike strings, lists are mutable, so you can assign to an index or even a slice:
Adding and removing items#
append vs extend is a classic mix-up: cart.append(["a", "b"]) adds one item (a nested list), while extend adds each element. remove raises ValueError if the value isn't there, and pop on an empty list raises IndexError.
Combining lists creates new ones:
Sorting#
There are two ways to sort, and the difference matters:
The key argument tells Python what to sort by. It takes a function that's applied to each item:
(lambda s: s[1] is a tiny inline function — you'll meet lambdas properly in the intermediate section.) Python's sort is stable: items that compare equal keep their original order, which lets you sort by several criteria in steps.
Other useful operations#
Unpacking#
Assign list items to separate names in one go. A starred name collects "the rest":
Copying: references vs copies#
Assignment never copies a list — it creates another name for the same object. To get an independent list, make a copy:
These are shallow copies: the new list holds references to the same inner objects. For nested lists, use copy.deepcopy:
The [[0] * n] * n trap
Lists as stacks and queues#
A list makes an excellent stack (last in, first out) with append and pop. For a queue (first in, first out), pop(0) is slow on big lists because every item shifts — use collections.deque instead:
Worked example: a grade report#
Common mistakes#
nums = nums.sort()—sort()returnsNone. Usenums.sort()ornums = sorted(nums).- Removing while iterating — build a new list instead:
nums = [n for n in nums if n >= 0]. - Confusing
appendandextend. - Assuming
b = acopies — it doesn't. - Using a list for membership tests on large data —
x in big_listscans every item. Sets (next lesson) do it instantly.
What's next#
Lists are flexible, but sometimes you want data that can't change, or a collection with no duplicates. Next up: tuples and sets.
Check your understanding
Quick quiz
1.What is the difference between
nums.sort()andsorted(nums)?2.What does
[1, 2] * 3produce?3.After
a = [1, 2, 3]andb = a[:], what doesb.append(4)do toa?
Finished reading?
Mark this lesson complete to track your progress.