List Methods Overview
In Python, there are several built-in functions that work on lists and make our life much easier. Here are some of the basics.
.append()
The .append() function allows us to add a new item to a list. It follows the format list_name.append(new_item).
rainbow_colors = [`"violet", "indigo", "blue", "green", "yellow", "orange", "red"]
rainbow_colors.append("black")
print(rainbow_colors)
OUTPUT
["violet", "indigo", "blue", "green", "yellow", "orange", "red", "black"]
We added the color "black" to the list using the .append() function.
len()
This built-in function allows us to access the length of the list. It becomes especially useful when we need to know the number of entries in a list for programs that work with lists of items.
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
print(len(rainbow_colors))
OUTPUT
7
.sort()
The .sort() function can be used to sort a list in ascending or descending order.
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
rainbow_colors.sort()
print("Ascending order: " + str(rainbow_colors))
rainbow_colors.sort(reverse=True)
print("Descending order: " + str(rainbow_colors))
OUTPUT
Ascending order: ['blue', 'green', 'indigo', 'orange', 'red', 'violet', 'yellow']
Descending order: ['yellow', 'violet', 'red', 'orange', 'indigo', 'green', 'blue']
Here we have sorted the list in both ascending and descending order. The default of .sort() is ascending order. To set it to descending order, set the reverse parameter of the .sort( argument to True.
This built-in method can come in handy when you need to sort lists by an id number, or you want to sort by value (like shopping websites do with prices listed low to high or high to low).