Wow, we made it to part 3 for lists from our original post on Python lists. In this blog post, we will look at Python list methods. List methods extend lists’ functionality, which can be found here in Python List Methods.
Unlike string methods that do not change the original string, list methods will change the list since they are mutable. To illustrate some of the methods, we are going to use a list of 10 random numbers.
ran_list
[100, 86, 15, 37, 96, 6, 68, 43, 73, 38]
The most common list methods are:
.append()
- Append lets you add what you put in the parenthesis at the end of the list
- An example if we want to append the integer 2 to the end of the list:
ran_list.append(2)
ran_list
[100, 86, 15, 37, 96, 6, 68, 43, 73, 38, 2]
.sort()
- Sort will sort the list in place.
- If we sort numbers, they will be sorted with the lowest number up to the largest number.
ran_list.sort()
ran_list
[2, 6, 15, 37, 38, 43, 68, 73, 86, 96, 100] - Sorting a list with mixed first letter cases will sort elements that begin with upper cases first.
ran_alpha = [‘cat’,’dog’,’whale’,’Cat’,’bird’,’shark’,’Shark’,’kitten’]
ran_alpha.sort() ran_alpha
[‘Cat’, ‘Shark’, ‘bird’, ‘cat’, ‘dog’, ‘kitten’, ‘shark’, ‘whale’] - If it\\\’s a mix of data types (alphanumeric), it will not sort. You will get a TypeError saying that it can not use the less-than comparison operator between a string and an integer.
[65,’cat’,99,’dog’,45,’whale’,3,’Cat’,32,’bird’,’shark’,’Shark’,’kitten’]
ran_alphanum =
ran_alphanum.sort()
Traceback (most recent call last): File “”, line 1, in TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
.reverse()
- Reverse will take a list and display it from greater to least, the opposite of sort.
ran_alpha.reverse()
ran_alpha
[‘whale’, ‘shark’, ‘kitten’, ‘dog’, ‘cat’, ‘bird’, ‘Shark’, ‘Cat’]
ran_list.reverse()
ran_list [100, 96, 86, 73, 68, 43, 38, 37, 15, 6, 2] - While there is a reverse method, you can do the same with sort. In the sort method call, passing reverse=True into the parenthesis of the method call:
ran_list1
[79, 67, 13, 53, 90, 8, 90, 64, 97, 3]
ran_list1.sort(reverse=True)
ran_list1
[97, 90, 90, 79, 67, 64, 53, 13, 8, 3]
- Reverse will take a list and display it from greater to least, the opposite of sort.
.insert()
- Insert allows you to pick an index and insert an object into the list.
- This object can be anything, even another list
- Insert nested list
ran_list1.insert(6,[‘this is my nested list’, 24,100,-100,1.23])
ran_list1
[97, 90, ‘cat’, 90, 79, 67, [‘this is my nested list’, 24, 100, -100, 1.23], 64, 53, 13, 8, 3]
.clear()
- This clears the contents of a list