Python course Β· Module 2: Data Structures
List Methods - Exploration Tools
In this lesson8
Welcome! Picture a morning at base camp. The first tracker comes back with news of a new species, the second asks you to put their sighting at the very top, and the third admits to recording one zebra twice. Your sighting journal is a list, and it has to keep up with all these changes. You could rebuild the list from scratch every time, but that is like copying out the whole journal just to add one line.
A list comes with built-in tools for this, called methods. A method is a function attached to a specific object, and you call it after a dot, for example sightings.append("Lion"). The dot tells Python: reach into this list's backpack and use the tool with this name.
Adding to the End - append()
The most common situation on the trail: a new discovery goes at the end of the journal. That is what the append() method is for. It takes one element and attaches it after the last entry.
1sightings = ["Tiger", "Elephant"]
2sightings.append("Python")
3print(sightings) # ['Tiger', 'Elephant', 'Python']There is no assignment with an = sign here: the list changed in place, and the earlier entries kept their order. That is exactly what it means for a list to be mutable.
The Trap: append() Returns Nothing
Since the method changes the list in place, it does not hand back a new list. It returns None, the "no value" you know from the first module. See what happens when someone tries to store its result:
1sightings = ["Tiger", "Elephant"]
2result = sightings.append("Lion")
3print(result) # None
4print(sightings) # ['Tiger', 'Elephant', 'Lion']The lion made it into the list, but result holds nothing. If someone wrote sightings = sightings.append("Lion"), the variable would lose the whole journal and point to None. The same rule applies to insert(), extend(), remove() and sort(): they change the list and return None.
Inserting in the Middle - insert()
Sometimes the position matters. You are planning a route and it turns out that a river flows between the camp and the waterfall. The insert() method takes two arguments: the index where the new element should stand, and the element itself.
1route = ["Camp", "Waterfall", "Finish"]
2route.insert(1, "River")
3print(route) # ['Camp', 'River', 'Waterfall', 'Finish']The river took index 1, and the waterfall and the finish moved one place to the right. Nothing disappeared or got overwritten. The call route.insert(0, "Start") would put a new point at the very beginning of the route.
Many Elements at Once - extend()
A second team arrives at the camp and you want to add all its members. It is tempting to use append(), but that method always adds exactly one element, even if that element is a whole list. Compare the two methods:
1team = ["Darwin", "Alice"]
2team.extend(["Maya", "Tom"])
3print(team) # ['Darwin', 'Alice', 'Maya', 'Tom']
4team.append(["Olivia", "Jack"])
5print(team) # ['Darwin', 'Alice', 'Maya', 'Tom', ['Olivia', 'Jack']]The extend() method added each person separately, while append() inserted the whole list as one element, so a list inside a list appeared at the end of the team. My advice: when you add several elements at once, reach for extend().
What About the + Operator?
You can also join lists with the + operator, but it works differently from the methods. It does not change either list, it builds a brand new one:
1base = ["Tiger"]
2bigger = base + ["Lion"]
3print(base) # ['Tiger']
4print(bigger) # ['Tiger', 'Lion']The base list stayed untouched. Remember this split: methods such as append() change the list in place, while the + operator and slicing, for example base[::-1], create a new list.
Removing by Value - remove()
The tracker who recorded the zebra twice asks for a correction. You know the name, but not the position, so you use the remove() method, which searches the list from the left and removes the first match.
1animals = ["Zebra", "Lion", "Zebra", "Python"]
2animals.remove("Zebra")
3print(animals) # ['Lion', 'Zebra', 'Python']Only the first zebra disappeared, the second one is still on the list. If the value is not there at all, Python raises a ValueError. So with uncertain data, first check that the value is there with the in operator:
1if "Hyena" in animals:
2 animals.remove("Hyena")
3print(animals) # ['Lion', 'Zebra', 'Python']There was no hyena, so the condition never let remove() run, and the list stayed unchanged.
Removing by Position - pop()
In the evening you take the last packed item out of your backpack to use it right away. This is where pop() helps: it is the only removing method you have met that hands back the removed element.
1supplies = ["Tent", "Map", "Compass"]
2last_item = supplies.pop()
3print(last_item) # Compass
4print(supplies) # ['Tent', 'Map']Without an argument, pop() takes and returns the last element, and with an index, for example supplies.pop(0), the given position. Which one should you choose? If you know the name, use remove(). If you know the position or need the removed element, use pop().
Finding and Counting - index() and count()
Not every tool changes the list. Two methods only read the journal: index() gives the position of the first occurrence, and count() counts all occurrences.
1sightings = ["Zebra", "Lion", "Zebra", "Elephant", "Zebra"]
2print(sightings.index("Lion")) # 1
3print(sightings.count("Zebra")) # 3After these calls the list looks exactly the same. Watch out for the difference when an element is missing: index() raises a ValueError, while count() calmly returns 0.
Sorting - sort() and sorted()
At the end of the day you want to order the animals' weights starting from the lightest. The sort() method does it in place:
1weights = [190, 5000, 3, 350]
2weights.sort()
3print(weights) # [3, 190, 350, 5000]The list is now sorted in ascending order, and the original order is gone. Just like append(), the sort() method returns None, so do not assign its result to a variable.
If the original order matters because it records the history of your sightings, use the sorted() function. It is not a method but a built-in function, so you pass the list inside the parentheses instead of putting it before a dot. The reverse=True parameter flips the sorting direction.
1weights = [190, 5000, 3, 350]
2ranking = sorted(weights, reverse=True)
3print(ranking) # [5000, 350, 190, 3]
4print(weights) # [190, 5000, 3, 350]The sorted() function returned a new list starting with the heaviest weight, while the weights list kept the order from the journal. The reverse=True parameter also works with the method: weights.sort(reverse=True). I recommend a simple rule: when you no longer need the old order, choose sort(), and when you want to keep it, choose sorted().
Everything Together
Finally, a short sequence in which one list goes through several tools in a row:
1numbers = [3, 1, 4]
2numbers.append(2)
3numbers.sort()
4print(numbers) # [1, 2, 3, 4]The 2 landed at the end, and then the sort() method put the numbers in ascending order. Both methods changed the same list, and we never assigned their result to a variable.
Remember: methods that change a list do it in place and, apart from pop(), return None, and when you want to keep the original, reach for sorted() or the + operator. In the next lesson Darwin will show you dictionaries, a catalog in which every discovery gets its own card.
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the append() method do on a list?
2. What does the pop() method return?
3. What is the difference between sort() and sorted()?
4. What does: lista.insert(0, 'X') do?
Hands-on tasks in the game
- Horizontal ordering
Arrange the call that adds every person from the list new_members to the list team:
- Code editor
Add 'Python' to the list animals = ['Tiger', 'Elephant']
- Code editor
Remove the last element from the list species = ['Tiger', 'Elephant', 'Parrot'] and print it
- Code editor
Sort the list numbers = [5, 2, 8, 1, 9] in ascending order
- Click in order
Click in order: animals.append('Python')
- Click in order
Click in order: sorted(numbers, reverse=True)
- Vertical ordering
Arrange the steps: create a list, add an element, sort, and print: