List Methods in Practice
Explore how to manipulate Python lists effectively by using methods to add, remove, organize, and locate data within lists. Understand how these dynamic structures evolve to support flexible data management essential for programming in Python.
We'll cover the following...
We learned earlier that lists are ordered sequences, but their real power lies in their flexibility. Unlike static data that we define once and never touch again, lists in Python are designed to evolve. We can build them up from scratch, filter out bad data, or rearrange items to make sense of chaos.
In this lesson, we will explore the tools Python provides to modify lists in place. Just as we used Python string methods to transform text, we use list methods to evolve our data structures.
Adding items to a list
The most common operation is adding new data to the list. Since lists are dynamic, we do not need to know their final size when we create them. We can start with an empty list and grow it as needed.
The append() method adds a single item to the absolute end. This is the most common way how to append to a list in Python when building a collection dynamically. We can call it through . operator as follows:
list.append()
Do not worry, if you are unfamiliar with the
.syntax. We'll study this in detail in later lesson.
It is fast and efficient. If we need to place an item at a specific position, we use insert(), which takes an index and the value to add.
Line 2: We define a list,
playlist, with two strings.Line 5:
append("Track C")adds the new string to the end of the list.Line 9:
insert(0, "Intro")places "Intro" at index 0, pushing "Track A" to index 1, "Track B" to index 2, and so on.Line 11: The final output shows the new order:
['Intro', 'Track A', 'Track B', 'Track C'].
Appending lists
A common question arises: "What happens if we pass a list into append?" Since append adds exactly one item to the end, it treats the entire new list as that single item. This creates a "nested list" (a list inside a list).
Line 6: We append
batch_2tobatch_1.Line 8: The length is now
4, not5.Line 9: The output is
[1, 2, 3, [4, 5]]. The inner brackets show that the second list is nested inside the first.
Merging lists
If our goal is to combine two lists into one flat sequence (e.g., [1, 2, 3, 4, 5]), append is not the right tool.
The manual way to solve this is by using a loop. We can iterate over the second list and append each item to the first list.
Line 5: We start a loop to look at every number in
batch_2.Line 6: We append each number individually to
batch_1.Line 8: The result is a flat list:
[1, 2, 3, 4, 5].
While this works, Python offers a cleaner, faster way. The extend() method does this exact loop for us internally. It takes a sequence (like a second list) and adds its contents to the end of the current list.
Line 5:
batch_1.extend(batch_2)automatically iterates overbatch_2and adds 4 and 5 tobatch_1.Line 7: The result is identical to the loop version:
[1, 2, 3, 4, 5].
Removing items
Python provides three primary ways to remove data from a list, depending on what we know about the item we want to delete.
remove(value): Deletes the first occurrence of a specific value. If the value isn't found, Python raises aValueError. Whileremove()handles single items, later we will combine these techniques to learn how to remove duplicates from a list in Python efficiently.pop(index): Removes the item at a specific index and returns it so we can use it. If no index is provided, it removes the last item.clear(): Wipes the entire list, leaving it empty.
Line 4: We use
.remove()to target an item by its content rather than its position. Python scans the list, deletes the first matching instance ("Meeting"), and automatically shifts subsequent items left to fill the gap.Line 7: We use
.pop()without arguments to remove the item from the end of the list. Crucially, this method returns the removed data, allowing us to capture "Lunch" in the variablecompleted_taskfor processing rather than just deleting it.Line 10: We use
.pop(0)to target a specific index. This allows us to extract the item at the very front of the queue ("Email"), demonstrating howpopcan be used to retrieve data from any specific location.Line 13: We use
.clear()to reset the list completely. Unlike deleting the variable itself, this removes all contents but keeps thetasksobject alive in memory as an empty list[], ready to accept new data.
Organizing data
There are two common operations performed on a collection of data: sorting and reversing. Python provides built-in support for each.
The sort() method arranges the elements. Knowing how to sort a list in Python is crucial for organizing everything from high scores to alphabetical contact lists. To sort the list in descending order, the method can be called with the argument reverse=True.
In contrast, the reverse() method does not perform any comparison-based sorting. Instead, it simply reverses the order of the elements in the list, flipping them from the end to the beginning regardless of their values.
Let's see them in action below.
Line 4:
scores.sort()changes the list to[15, 42, 88, 99]. It does not create a new list.Line 8:
scores.sort(reverse=True)resorts the list to[99, 88, 42, 15].Line 12:
scores.reverse()flips the current order to[15, 42, 88, 99].
Both sort() and reverse() modify the list directly and return None. A common mistake is assigning the result of these methods to a new variable, such as sorted_list = my_list.sort(). This does not create a sorted list; instead, it assigns None to sorted_list. As a result, the new variable does not reference the list at all.
Locating data
When working with lists, it is often necessary to determine where a particular item is located or how frequently it appears. Python provides two built-in methods for these purposes: index() and count().
index(value): Theindex()method returns the position of the first occurrence of thevaluein the list and raises aValueErrorif it is not present.count(value): Thecount()method, on the other hand, returns the total number of times thevalueappears in the list. If it is not present, thecount()method returns0.
Let's see them in action below.
Line 4:
guests.index("Bob")scans the list and returns1.Line 7:
guests.count("Alice")scans the entire list and returns2because "Alice" appears twice.Line 9–10: We print the results:
Bob is at index: 1, andAlice appears: 2 times.
We have now seen how lists function as mutable collections that can be expanded, reduced, and reorganized as needed. This flexibility makes lists a foundational and widely used data structure in Python. However, there are situations in which data must remain unchanged, e.g., sequences intentionally fixed to ensure consistency, safety, and structural integrity. In the next lesson, we will introduce Python tuples, which provide exactly the form of immutability and stability we need.