We will look upon the basic list methods in this tutorial.
Let us take the list my_list= [1,2,3].
1. append() →
The append method is used to add an element to our list. Suppose we want to add the string “Python is Awesome!” and the float value 3.15 to our list. Then, we use the append method as shown below-
my_list.append("Python is Awesome!") my_list.append(3.15) print(my_list)
Then, we run the code and our new updated list gets printed out.
[1, 2, 3, 'Python is Awesome!', 3.15]
Note that the new items get added to the end of the list.
2. pop() →
The pop method is used to remove an element at a specific index from the list. So, if we want to remove the element 2 (at index 1), then we use the pop method as shown below-
And the list gets printed out –
[1, 3, 'Python is Awesome!', 3.15]
3. sort() →
The sort method is used to sort the list. We can sort the list in both ascending and descending order. Let’s take a new list –
As we can see, the list is not sorted in any manner. Let’s sort it in ascending order (sort() method by default sorts the list in ascending order)-
And here’s the sorted list-
[1, 2, 3, 5, 90]
Now, let’s sort the list in reverse order (descending order)-
And here’s our list in descending order-
[90, 5, 3, 2, 1]
The reverse method is used to reverse a list. Let’s try this method on the final form of my_list.
And our reversed list gets printed out-
[3.15, 'Python is Awesome!', 3, 1]
That’s it for this time folks! We will see some more advanced properties and methods of lists later on.