28th Sep 2022 11 minutes read An Overview of Python List Methods Juliano Luiz Faccioni python list Learn how to modify lists in Python using list methods – specialized operations that give you tons of flexibility. Python lists have a lot of functionality that you can leverage in your scripts. This includes common sequence operations like adding elements to a list, reordering elements, and counting the number of times a given element appears in a list. Collectively, these operations are called list methods. In this article, we will go through an overview of Python’s main list methods. If you want a deeper dive into Python as a whole, be sure to check out our Python Basics track. It includes 3 full courses and over 35 hours’ worth of learning material. But What Exactly Are Python List Methods? The word “method” may sound weird at first, but do not worry: Methods in Python are very similar to traditional Python functions, like print(), sum(), or len(). In fact, methods work exactly like functions, except they are associated with specific data types like integers, strings, or lists. In this sense, you can think of methods as specialized functions that are designed to work with a particular type of data. Each data type has their own set of methods. An important distinction between methods and functions is how to run them. Regular functions are executed by writing their name and using parentheses to (optionally) pass in some arguments. It looks like this: result = some_function(argument1, argument2) Methods, on the other hand, must be accessed and executed from a variable. You do this by adding a period between the variable and the method name: result = some_variable.some_method(argument1, argument2) Notice the period before some_method? This indicates that we are using a method. The data type of some_variable determines which methods are available. Here’s a concrete example, where we define the variable values (a list) and then call its append() method with 8 as its argument: values = [1, 5, 10] values.append(8) # here we modify the "values" list If you’re confused about variables and functions, the Python Basics track will get you up to speed in no time. Now that we know how methods work, let’s have an overview of the main Python list methods, and what they are used for. Note: In the examples below, we are using the notation list.method_name() to indicate that these methods belong to lists. When writing code, remember to replace list with the actual variable that you want to use when calling the method. Add Elements to a Python List with list.append() We will start with one of the most common list operations: we’ll put elements into a Python list. You can do this with the list methods list.append(), list.insert(), and list.extend() – with each method working in a slightly different way. For example, using list.append(x) will simply place the element x at the end of the list. Take a look at the example below: numbers = [1, 2, 3, 4] numbers.append(5) print(numbers) # output: [1, 2, 3, 4, 5] The list.append() method takes one argument, which is the element to add to the list. In this case, we appended the number 5 to the end of the list. There are a few things to take note here: For the sake of simplicity, the list numbers contains only integers. But Python lists can have elements of any type in them – or even multiple types in the same list. The example works just as well if we modify it to numbers.append("hello") or numbers.append(True). You might have expected the list.append() method to return a value, something like result = numbers.append(5). However, most list methods in Python happen “in-place”; the original list is modified and nothing is returned. In fact, if you executed the code, you would see that result ends up being a None value. Both of these facts are natural consequences of lists being mutable sequences. This is yet another concept explored in depth in our Python Basics track! Insert Elements into a Python List with list.insert() list.insert() works similarly to list.append(), but you need to provide the index where the element will be inserted to the list. Take a look at the example below: animals = ["cat", "dog", "fish"] animals.insert(1, "monkey") print(animals) # output: ["cat", "monkey", "dog", "fish"] We inserted the element "monkey" at index 1, which corresponds to the second position in the list. (Remember: in Python, the indices start at zero.) The second and third elements ("dog" and "fish", respectively) are pushed to the end to make room for the element being inserted. A great feature of list.insert() is that you don’t need to check the size of the list beforehand; no errors are raised if the index is larger than the size of the list. Instead, the list.insert() method simply puts the element at the end, working much like list.append() in this situation. Look at this example: animals = ["cat", "dog", "fish"] animals.insert(200, "monkey") print(animals) # output: ["cat", "dog", "fish", "monkey"] Even though the original list does not have an element at index 200, the code still places the new element "monkey" at its end. Another useful feature for list.insert() is to use an index of 0, which always inserts the element at the start of the list. Append Multiple Elements to a Python List with list.extend() list.extend() is yet another way to add elements to a Python list. It’s useful when you want to add multiple elements at once. It’s easier to understand how list.extend() works if we try to append a list to another list. Look what happens: things = ["John", 42, True] other_things = [0.0, False] things.append(other_things) print(things) # output: ["John", 42, True, [0.0, False]] When we write things.append(other_things), the other_things list is considered as a single element, and we end up with a nested list. But what if we wanted to add every element from other_things into the things list? This is exactly where list.extend() is useful: things = ["John", 42, True] other_things = [0.0, False] things.extend(other_things) print(things) # output: ["John", 42, True, 0.0, False] No nested lists! As you can see, the list.extend() method appends each individual element from the list passed in as an argument. Remove an Element from a Python List with list.remove() Unsurprisingly, the list.remove() method is used to remove a value from a list. The first element that matches the argument is simply taken from the list. But watch out: An error is raised if the element is not present in the list! Here you can see the list.remove() method in action: booleans = [True, False, True, True, False] booleans.remove(False) # Removes the first False value print(booleans) # output: [True, True, True, False] booleans.remove(False) # Removes the other False value print(booleans) # output: [True, True, True] booleans.remove(False) # ValueError! No more False values to remove Take an Element from a Python List with list.pop() The list.pop() method is used to take the element from the list. By default, it takes the element from the end of the list. However, you can also pass an index as an argument and it will take the element at that index instead. Here’s the list.pop() method in action: fruits = ["apple", "orange", "banana", "peach"] last_fruit = fruits.pop() # takes the last element print(last_fruit) # output: "peach" second_fruit = fruits.pop(1) # takes the second element ( = index 1) print(second_fruit) # output: "orange" print(fruits) # only fruits that have not been "popped" # are still in the list # output: ["apple", "banana"] You may have noticed that the fruits being “popped” from the list are actually returned, so we can save them to variables like last_fruit and second_fruit. This means that you can use list.pop() to remove values from lists but still access them later on in your code. Also, do watch out for the errors that occur if you use list.pop() on an empty list or if you pass in an index larger than the size of your list! Delete All Items from a Python List with list.clear() This one is short and sweet: If you call the list.clear() method, all values are discarded and the list ends up empty. Here’s how this looks: decimals = [0.1, 0.2, 0.3, 0.4, 0.5] decimals.clear() # remove all values! print(decimals) # output: [] As expected, the decimals list was emptied after calling its list.clear() method. Count Elements in a Python List with list.count() list.count() is another straightforward list method in Python: It simply counts the number of occurrences of its argument inside the list. This number is returned by the method, so we can use a variable to save it. In the example below, we count the number of students whose exam grade was equal to 10.0: grades = [7.8, 10.0, 7.9, 9.5, 10.0, 6.5, 9.8, 10.0] n = grades.count(10.0) print(n) # output: 3 Locate Elements in a Python List with list.index() The list.index() method is a bit more complex: Given an argument, it returns the position (index) where the argument appears in the list. Take a look at this example: friends = ["John", "James", "Jessica", "Jack"] position = friends.index("Jessica") print(position) # output: 2 As shown above, the list.index() properly returned the value 2, indicating that the element "Jessica" appears at that index in the list. The list.index() method will raise an error if the argument is not found on the list. One way to work around this is to use an if/else block to check if the element is in the list beforehand. Here’s an example: friends = ["John", "James", "Jessica", "Jack"] name = "Jessica" if name in friends: position = friends.index(name) # guaranteed to not raise an error print("Friend", name, "is at position", position) else: print("Friend", name, "not in list") Change the name variable to a name that is not in the list, and you’ll see the code reach the else block with no errors being raised! Reorder Elements in a Python List with list.sort() and list.reverse() The list.sort() and list.reverse() methods can be used to reorder elements in the list. As you may expect, list.sort() sorts the values, while list.reverse() reverses the position of every value in the list. Here’s how these Python list methods look in action: values = [10, 4, -2, 1, 5] values.reverse() print(values) # list is reversed # output: [5, 1, -2, 4, 10] values.sort() print(values) # list is sorted # output: [-2, 1, 4, 5, 10] If you want to sort the values in descending order, you could first call list.sort(), then list.reverse() afterwards. But this is such a common operation that Python allows you to perform both at the same time: Simply add the reverse=True argument when calling list.sort(). Have a look: values = [10, 4, -2, 1, 5] values.sort(reverse=True) print(values) # list is sorted in reverse order # output: [10, 5, 4, 1, -2] Note: To sort a list in Python, you need to be able to compare the values among themselves and figure out which values are greater than the others. This means that you cannot sort a list that contains multiple data types, like strings and numbers. It doesn’t make sense to ask if the number 10 is greater than the string "John"! Create an Independent Copy of a Python List with list.copy() The list.copy() is used to create an independent copy of a list. This is important because several variables may reference the same list. In this case, the variables are not independent copies, but rather simply references to the same underlying list object. To better understand this concept, look at the code below: values_01 = [1, 2, 3, 4] values_02 = values_01 # not an actual copy: same list object! values_02.append(5) # we modify the "values_02" list... print(values_01) # ... but changes appear also in "values_01" # because they reference the same list! # output: [1, 2, 3, 4, 5] This surprises a lot of newcomers to Python, since they expect the values_01 list not to change when something is appended to values_02. But in reality, both lists values_01 and values_02 are references to the same underlying list! The proper way to create independent lists is to use the list.copy() method: values_01 = [1, 2, 3, 4] values_02 = values_01.copy() # create an independent copy! values_02.append(5) # we modify the "values_02" list... print(values_01) # ... and changes DO NOT appear in "values_01" # because it is a copy! # output: [1, 2, 3, 4] Mastering List Methods in Python We just went through an overview of list methods in Python, but you’re only getting started! If you’re interested in learning more about Python methods, read this article for an overview of Python string methods. And if you want more content on lists, be sure to check out this article and discover where to find good list exercises. You can also learn more with our recommended YouTube Python channels. And don’t forget about all of our resources at LearnPython.com – you’re at the best place to learn Python, after all! Tags: python list