List Methods
Now let’s look at some additional list methods that help us sort, reverse, count, and copy list items. We have discussed methods like append(), clear(), extend(), insert(), pop(), remove() before. Now we will learn about some more list methods:
sort():
This method sorts the list in ascending order.
Example 1:
colors = ["violet", "indigo", "blue", "green"]
colors.sort()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)Output:
['blue', 'green', 'indigo', 'violet']
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]What if you want to print the list in descending order?
We must give reverse=True as a parameter in the sort method.
Example:
colors = ["violet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort(reverse=True)
print(num)Output:
['violet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]The reverse parameter is set to False by default.
Note: Do not confuse the reverse parameter with the reverse() method. The reverse=True option works only inside the sort() method and sorts the list in descending order, while the reverse() method simply reverses the current order of the list and does not perform any sorting.
reverse():
This method reverses the order of the list.
Example:
colors = ["violet", "indigo", "blue", "green"]
colors.reverse()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.reverse()
print(num)Output:
['green', 'blue', 'indigo', 'violet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]index():
This method returns the index of the first occurrence of the list item.
Example:
colors = ["violet", "green", "indigo", "blue", "green"]
print(colors.index("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))Output:
1
3Note: If the item is not present in the list, index() will raise a ValueError.
count():
Returns the count of the number of items with the given value.
Example:
colors = ["violet", "green", "indigo", "blue", "green"]
print(colors.count("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.count(2))Output:
2
3copy():
Returns a copy of the list. This can be done to perform operations on the list without modifying the original list.
Example:
colors = ["violet", "green", "indigo", "blue"]
newlist = colors.copy()
print(colors)
print(newlist)Output:
['violet', 'green', 'indigo', 'blue']
['violet', 'green', 'indigo', 'blue']