Lists
A list holds many values in one variable, in order: the items in a shopping cart, the marks of a class, the stations on a train route. Lists are the most used collection in Python, and they can grow, shrink and change at any time.
In this lesson you will create lists, read and change their items, add and remove items, search and sort them, and learn the copying rule that causes some of the most confusing bugs in Python.
Creating a list
Write the items inside square brackets, separated by commas. A list can hold any type of value, even a mix, and it can be empty.
stations = ["Delhi", "Panipat", "Ambala", "Ludhiana", "Jalandhar"]
marks = [72, 45, 91, 60]
empty = []
print(stations)
print(len(stations), "stations")
print(stations[0], stations[-1])
print(stations[1:3])['Delhi', 'Panipat', 'Ambala', 'Ludhiana', 'Jalandhar'] 5 stations Delhi Jalandhar ['Panipat', 'Ambala']
Indexing and slicing work exactly as they do for strings (see Strings): the first item is at index 0, -1 is the last, and a slice like [1:3] gives a new list that stops before index 3. Asking for an index that does not exist gives IndexError: list index out of range.
Lists can change
Unlike strings, lists are mutable: you can change them in place. Assign to an index to replace an item.
cart = ["rice", "dal", "oil"]
cart[2] = "ghee" # replace an item
cart.append("tea") # add to the end
cart.insert(1, "sugar") # add at position 1
cart.extend(["salt", "atta"]) # add several items
print(cart)['rice', 'sugar', 'dal', 'ghee', 'tea', 'salt', 'atta']
append(item)adds one item to the end. This is the one you will use most.insert(index, item)adds an item at a position and shifts the rest along.extend(other_list)adds every item from another list.cart + ["salt"]also joins lists, but it makes a new list instead of changingcart.
Watch out for cart.append(["salt", "atta"]): it adds the whole list as one item, giving a list inside a list.
Removing items
cart = ["rice", "sugar", "dal", "ghee", "tea"]
cart.remove("sugar") # remove by value
last = cart.pop() # remove and return the last item
first = cart.pop(0) # remove and return the item at index 0
del cart[0] # delete by index
print("Removed:", last, "and", first)
print("Left:", cart)Removed: tea and rice Left: ['ghee']
| Way to remove | Use it when |
|---|---|
remove(value) | You know the value; it removes the first match only |
pop() / pop(i) | You want the removed item back |
del items[i] | You know the position and do not need the item |
clear() | You want to empty the whole list |
remove() raises ValueError: list.remove(x): x not in list if the value is missing, so check with in first when you are not sure.
Searching and simple maths
The in operator, index() and count() search a list, and the built-in functions len(), sum(), min() and max() work on lists of numbers.
marks = [72, 45, 91, 60, 91]
print(91 in marks)
print(marks.index(91))
print(marks.count(91))
print(f"Highest {max(marks)}, lowest {min(marks)}, average {sum(marks) / len(marks):.1f}")True 2 2 Highest 91, lowest 45, average 71.8
index() gives the position of the first match.
Sorting: sort() and sorted()
There are two ways to sort, and mixing them up is a classic mistake:
items.sort()sorts the list in place and returnsNone.sorted(items)returns a new sorted list and leaves the original alone.
marks = [72, 45, 91, 60]
ranked = sorted(marks, reverse=True)
print(ranked)
print(marks)
marks.sort()
print(marks)
names = ["meera", "Aarav", "kabir"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(sorted(names, key=len))[91, 72, 60, 45] [72, 45, 91, 60] [45, 60, 72, 91] ['Aarav', 'kabir', 'meera'] ['Aarav', 'kabir', 'meera'] ['meera', 'Aarav', 'kabir']
reverse=True sorts from largest to smallest. key= tells Python what to compare: key=str.lower sorts names without caring about capital letters, and key=len sorts by length. Names of equal length keep their original order. You will write your own key functions in Lambda Functions.
Copying lists: the aliasing trap
This is the most important idea in this lesson. Assignment never copies a list. b = a makes b a second name for the same list, so a change through one name is visible through the other. This is called aliasing.
original = ["Aarav", "Priya"]
same = original
same.append("Kabir")
print(original)
copy = original.copy()
copy.append("Isha")
print(original)
print(copy)
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid)['Aarav', 'Priya', 'Kabir'] ['Aarav', 'Priya', 'Kabir'] ['Aarav', 'Priya', 'Kabir', 'Isha'] [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
original.copy() (or list(original), or original[:]) makes a real, separate list. The last part builds a 3 by 3 grid, a list of lists, and grid[0][0] means "row 0, column 0". It uses a comprehension, which you will learn next in Comprehensions. The shortcut [[0] * 3] * 3 looks the same but repeats one inner list three times, so changing grid[0][0] would change the first item of every row.
You can also unpack a list into variables: first, *rest = [1, 2, 3, 4] puts 1 in first and [2, 3, 4] in rest.
Common mistakes
marks = marks.sort().sort()returnsNone, so this throws your list away. Writemarks.sort()on its own, ormarks = sorted(marks).- Thinking
b = acopies a list. It does not; both names share one list. Usea.copy(). append()with a list.cart.append(["a", "b"])adds one nested list. Useextend()to add each item.- Removing items while looping over the same list. Python skips items. Build a new list instead.
Key points
- A list is an ordered, changeable collection written in square brackets.
- Indexing and slicing work like strings;
items[i] = xchanges an item. append(),insert()andextend()add items;remove(),pop(),delandclear()remove them.sort()changes the list and returnsNone;sorted()returns a new list. Both acceptkey=andreverse=True.b = adoes not copy; usea.copy()for a separate list.len(),sum(),min(),max()andinwork on lists.
Exercise
Start with the waiting list for a cooking class: waiting = ["Rohan", "Ananya", "Farhan"]. Add "Isha" to the end and "Meera" to the front. Farhan cancels, so remove him. Then take the first person off the list with pop(0) and print "Seat given to ...". Finally print the remaining list in alphabetical order without changing the original order of waiting, and print waiting too.
Show solution
waiting = ["Rohan", "Ananya", "Farhan"]
waiting.append("Isha")
waiting.insert(0, "Meera")
waiting.remove("Farhan")
lucky = waiting.pop(0)
print("Seat given to", lucky)
print(sorted(waiting))
print(waiting)Seat given to Meera ['Ananya', 'Isha', 'Rohan'] ['Rohan', 'Ananya', 'Isha']
insert(0, ...) puts Meera first, so pop(0) gives her the seat. sorted() returns a new list, so waiting keeps its first-come order.
Quick Quiz
1. What does [10, 20, 30, 40][1:3] give?
The slice starts at index 1 and stops before index 3.
2. After marks = [3, 1, 2] and result = marks.sort(), what is result?
sort() sorts the list in place and returns None; use sorted() for a new list.
3. After a = [1, 2], b = a and b.append(3), what is a?
b = a makes both names refer to the same list, so the change shows through a.
4. Which method adds every item of another list to the end?
extend() adds each item separately; append() would add the whole list as one item.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
