Introduction & Syntax
Lists · Study material
The list is Python's workhorse collection: an ordered, mutable sequence that can hold items of any type and grows and shrinks as needed. Shopping carts, marks, rows of a file, stacks of undo steps – all lists. Because lists are mutable, they are also the source of the most famous Python traps: sort() returning None, append vs extend, the [[0] * 3] * 3 grid, and two names sharing one list. This topic covers creation, indexing, every list method, sorting, nested lists and copying, then 50 practice questions run on Python 3.
On this page
- Creating lists, indexing and slicing
- List methods: append, extend, insert, remove, pop, index, count …
- Changing items and slices; del
- sort() vs sorted(), key and reverse
- min, max, sum and unpacking
- Nested lists, aliasing and copies
Creating and reading lists
Write items in square brackets, or convert any iterable with list(). Lists support everything strings do – indexing, negative indexes, slicing, len(), in, + and * – but unlike strings they can be changed.
marks = [78, 85, 91] # a list literal
mixed = ["Asha", 21, 8.7, True] # items can be of any type
empty = []
letters = list("abc") # list() turns any iterable into a list
evens = list(range(0, 10, 2))
print(marks, len(marks))
print(mixed[0], mixed[-1], letters, evens, empty)
print(marks[0:2], marks[::-1], 85 in marks)
[78, 85, 91] 3 Asha True ['a', 'b', 'c'] [0, 2, 4, 6, 8] [] [78, 85] [91, 85, 78] True
List methods
| Method | Effect | Returns |
|---|---|---|
append(x) | add x as ONE item at the end | None |
extend(iterable) | add each item of the iterable | None |
insert(i, x) | insert x before index i | None |
remove(x) | remove the first item equal to x (ValueError if absent) | None |
pop(i=-1) | remove the item at i (IndexError if empty) | the item |
index(x), count(x) | position of first x / number of x | int |
sort(), reverse() | reorder in place | None |
copy(), clear() | shallow copy / empty the list | list / None |
Methods that change the list return None – so never write lst = lst.sort().
cart = ["pen", "book"]
cart.append("bag") # add ONE item at the end
cart.extend(["ink", "tape"]) # add EACH item of an iterable
cart.insert(1, "ruler") # insert before index 1
print(cart)
cart.remove("ink") # remove the first matching VALUE
last = cart.pop() # remove and return the last item
first = cart.pop(0) # … or the item at an index
print(cart, last, first)
print(cart.index("book"), cart.count("pen"))
del cart[0] # delete by index (or slice)
print(cart)
cart.clear()
print(cart)
['pen', 'ruler', 'book', 'bag', 'ink', 'tape'] ['ruler', 'book', 'bag'] tape pen 1 0 ['book', 'bag'] []
Changing items and slices
Assign to an index to replace one item, or to a slice to replace a whole range – the replacement may be shorter or longer. An extended slice (with a step) must receive exactly as many items as it selects. del lst[i] or del lst[a:b] removes by position.
nums = [10, 20, 30, 40, 50]
nums[0] = 11 # replace one item
nums[1:3] = [21, 22, 23] # slice assignment may change the length
print(nums)
nums[::2] = [0, 0, 0] # an extended slice needs the same number of items
print(nums)
del nums[-2:]
print(nums)
[11, 21, 22, 23, 40, 50] [0, 21, 0, 23, 0, 50] [0, 21, 0, 23]
Sorting: sort() vs sorted()
lst.sort() sorts in place and returns None; sorted(iterable) returns a new list and works on any iterable. Both take key= (a function applied to each item before comparing) and reverse=True. Python's sort is stable: items with equal keys keep their original order, which lets you sort by several criteria. Items must be comparable – mixing str and int raises TypeError.
scores = [72, 95, 58, 88]
ranked = sorted(scores, reverse=True) # sorted(): a NEW list, original untouched
print(ranked, scores)
result = scores.sort() # .sort(): sorts IN PLACE and returns None
print(scores, result)
names = ["meera", "Ravi", "asha", "Kiran"]
print(sorted(names)) # uppercase before lowercase
print(sorted(names, key=str.lower)) # case-insensitive
print(sorted(names, key=len)) # by length; ties keep their order (stable sort)
students = [("Asha", 91), ("Ravi", 78), ("Meera", 91)]
print(sorted(students, key=lambda s: (-s[1], s[0]))) # marks high→low, then name
[95, 88, 72, 58] [72, 95, 58, 88]
[58, 72, 88, 95] None
['Kiran', 'Ravi', 'asha', 'meera']
['asha', 'Kiran', 'meera', 'Ravi']
['Ravi', 'asha', 'meera', 'Kiran']
[('Asha', 91), ('Meera', 91), ('Ravi', 78)]min, max, sum and unpacking
min(), max() (both accept key=) and sum() replace most hand-written loops. Unpacking assigns items to names; a starred name collects the rest as a list.
temps = [31, 28, 35, 30, 29]
print(min(temps), max(temps), sum(temps), sum(temps) / len(temps))
print(max([-7, 3, -9], key=abs)) # the item with the largest absolute value
first, second, *others = temps # starred unpacking
print(first, second, others)
*_, last = temps
print(last)
for i, t in enumerate(temps, 1):
if t == max(temps):
print("Hottest: day", i)
28 35 153 30.6 -9 31 28 [35, 30, 29] 29 Hottest: day 3
Nested lists
A list of lists represents a table or matrix: m[row][col]. Never build one with [[0] * n] * m – the outer * repeats a reference to the same inner list, so changing one row changes them all. Use a comprehension so every row is a new list.
matrix = [[1, 2, 3],
[4, 5, 6]]
print(matrix[1][2], len(matrix), len(matrix[0])) # row 1, column 2
for row in matrix:
print(" ".join(str(x) for x in row))
# The trap: * copies REFERENCES, so all three rows are the same list
bad = [[0] * 3] * 3
bad[0][0] = 9
print(bad)
good = [[0] * 3 for _ in range(3)] # a new row on every pass
good[0][0] = 9
print(good)
6 2 3 1 2 3 4 5 6 [[9, 0, 0], [9, 0, 0], [9, 0, 0]] [[9, 0, 0], [0, 0, 0], [0, 0, 0]]
Aliasing, += and copies
b = a makes b another name for the same list. a += [x] extends that list in place (b sees it), while a = a + [x] builds a new list. copy(), list(a) and a[:] make a shallow copy: a new outer list whose items are the same objects – nested lists are still shared. copy.deepcopy() copies everything.
a = [1, 2]
b = a # alias: same list
a += [3] # += EXTENDS the list in place – b sees it
print(a, b, a is b)
a = a + [4] # + builds a NEW list and rebinds a – b does not see it
print(a, b, a is b)
orig = [[1, 2], [3, 4]]
shallow = orig.copy() # also list(orig) or orig[:]
shallow.append([5]) # the outer list is independent …
shallow[0].append(99) # … but the inner lists are shared
print(orig)
[1, 2, 3] [1, 2, 3] True [1, 2, 3, 4] [1, 2, 3] False [[1, 2, 99], [3, 4]]
Common mistakes
- lst = lst.sort() – lst becomes None.
- append(list) when extend was meant – creates a nested list.
- [[0] * n] * m – rows share one list.
- Removing items while looping – items are skipped.
- lst[len(lst) / 2] – a float index is a TypeError; use //.
- remove()/pop() without checking – ValueError / IndexError.
- Sorting mixed types – TypeError in Python 3.
Key points to remember
- Lists are ordered, mutable and can hold any types.
- append adds one item; extend adds many.
- Mutating methods return None.
- sorted() returns a new list; sort() works in place; both are stable.
- remove() is by value, pop() and del by position.
- = aliases; copy() is shallow; deepcopy() is deep.
- Build 2-D lists with a comprehension.
Frequently asked questions
List or tuple?
Use a list for a collection that changes; a tuple for a fixed record or as a dictionary key. See the Tuples topic.
Are Python lists arrays?
They are dynamic arrays of references: indexing and append are fast (O(1)), inserting or removing at the front is slow (O(n)). For numeric arrays use the array module or NumPy.
How do I remove duplicates from a list?
list(dict.fromkeys(lst)) keeps the order; list(set(lst)) does not guarantee it.
Where can I learn more?
Read Python Lists and Python List Comprehensions in the Python tutorial, then practise with the exercises below.