Programming and IT
Python: lists
A list is a mutable, ordered collection of values of any type. It is also the main source of surprises for beginners: assignment does not copy a list, sort returns nothing, and removing items inside a loop skips half of them. Let us go through it in order.
In this article
Creating a list and what goes inside#
A list is written in square brackets; the items can be of different types, and that is fine, although in real code a list of one type is easier to work with.
=
=
=
# 3 3 2
Indexing starts at zero, and negative indexes count from the end: -1 is the last
item. Going past the end raises IndexError rather than returning an empty value.
Adding and removing#
=
# ['a', 'b', 'c']
# ['a', 'b', 'c', 'd', 'e']
# ['a', 'x', 'b', 'c', 'd', 'e']
# removes the FIRST occurrence
= # 'e', the list got shorter
# ['a', 'b', 'c', 'd'] e
Learn the difference between append and extend right away: the first adds its
argument as a single item, the second unpacks it item by item.
=
# [1, 2, [3, 4]]
=
# [1, 2, 3, 4]
remove raises ValueError if the value is not there, and pop(i) raises
IndexError for a bad index. To delete by index without getting the value back,
use del items[0].
Sorting: sort and sorted#
=
# ['plum', 'melon', 'Apple']
# ['plum', 'melon', 'Apple']
# None
# ['Apple', 'melon', 'plum']
The sort method changes the list in place and returns None — the line
words = words.sort() turns your list into None, and that is a common mistake.
The sorted function returns a new list and works with any sequence. The key
argument says what to compare by: key=len — by length, key=str.lower —
ignoring case. A capital letter compares by its character code and therefore comes
before lowercase letters: Apple landed before melon. Sorting is stable — items
with equal keys keep their original order: in the key=len example, the
five-letter melon and Apple stayed in the order they were in.
Copying: assignment does not copy#
=
=
# [1, 2, 3, 4] — a changed too
= # or list(a), or a[:]
# [1, 2, 3, 4] [1, 2, 3, 4, 5]
b = a gives a second name to the same object. A real copy is a.copy(),
list(a) or the slice a[:]. But all three are shallow copies: nested lists stay
shared.
=
=
= 9
# [[9, 0], [0, 0]]
For a deep copy, use copy.deepcopy. For the same reason, grid = [[0] * 3] * 3
is dangerous: the outer list gets three references to one row, and
grid[0][0] = 1 changes all three. The right way is [[0] * 3 for _ in range(3)].
List comprehensions and iteration#
=
# [0, 1, 4, 9, 16]
# [0, 4, 16]
# 1 a / 2 b
A list comprehension reads as "what to collect — from what — under which
condition", and it is almost always shorter than a loop with append.
A separate trap is changing a list while a loop is going over it:
=
# [1, 2, 3] — one 2 survived
The loop walks by index, and the list shifted after the removal. The right
approach is to build a new list: nums = [n for n in nums if n != 2].
An exercise to make it stick: from the list of scores [4, 5, 3, 5, 4, 2], get a
list without duplicates sorted in descending order, and separately the number of
scores above three. Each answer fits on one line.
Related topics: Python slicing for taking pieces of a list, and Python dictionaries for when you need access by key rather than by position.
Step-by-step plan
- Create and loopA list of ten numbers: print its length, the first and last item, then loop with enumerate.
- Five changing methodsappend, extend, insert, remove, pop — print the list after each one and see the difference.
- Sort three wayssort, sorted, sorted with key=len; make sure sort returned None.
- A copying experimentb = a and c = a.copy(): change each one and compare what happened to a.
- Rewrite a loop as a comprehensionReplace a loop with append by a list comprehension with a condition.
Start learning this in your own space
The plan goes into your repository: tick off stages, keep notes — the change history shows how far you have come.
Check yourself
1.What does this print: a = [1, 2]; a.append([3, 4]); print(len(a))?
2.What does print([1, 2, 3].sort()) print?
3.What does this print: a = [1, 2]; b = a; b.append(3); print(a)?
4.What is len([x for x in range(10) if x % 3 == 0])?
Sources
-
Data Structures in the Python tutorialList methods, list comprehensions, stacks and queuesfree
-
Built-in types: sequencesReference for operations on list and other sequencesfree
-
Sorting TechniquesThe official guide to sort, sorted and key functionsfree
Was this helpful?