Lists in Python
Making, indexing and slicing lists, the methods worth memorising, and the mutable-default trap.
5 minute read · Free · Taught properly in our Python Training in Amritsar
A list holds an ordered run of values. They can be of different types, though in practice you usually keep one kind in one list.
marks = [88, 72, 95, 61]
mixed = [1, "two", 3.0, True]
empty = []
Getting things out
marks[0] # 88 — counting starts at zero
marks[3] # 61
marks[-1] # 61 — last item
marks[-2] # 95 — second from the end
Negative indexes count backwards. marks[-1] is the idiomatic way to get the last item; do not write marks[len(marks) - 1].
Slicing
marks[1:3] # [72, 95] — from 1, stop before 3
marks[:2] # [88, 72] — from the start
marks[2:] # [95, 61] — to the end
marks[:] # a full copy
The end is always exclusive, same as range(). Once that clicks, slicing stops being confusing.
The methods you will actually use
marks.append(70) # add one at the end
marks.insert(0, 100) # add at a position
marks.remove(72) # delete by value (first match only)
last = marks.pop() # remove and return the last
marks.sort() # sort in place
marks.reverse() # flip in place
len(marks) # how many
95 in marks # True or False
Note which ones return something and which change the list in place. sorted(marks) gives you a new sorted list; marks.sort() returns None and changes the original. Writing marks = marks.sort() sets marks to None, and then nothing works. We see it most weeks.
The trap worth knowing early
Never use a list as a default argument:
def add_student(name, batch=[]): # wrong
batch.append(name)
return batch
add_student("Ravi") # ['Ravi']
add_student("Simran") # ['Ravi', 'Simran'] — the same list!
The default is created once, when the function is defined, not each time it is called. Do this instead:
def add_student(name, batch=None):
if batch is None:
batch = []
batch.append(name)
return batch
This one appears in interviews, so it is worth being able to explain rather than just avoid.
Stuck on this in your own code?
That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.