RUN
C C++ JAVA PYTHON SQL HTML CSS DSA Robotics AWS CODING INTERVIEW PREPARATION

Made with  & Code

# Methods in Python

Written By -

We will look upon the basic list methods in this tutorial.

## List Methods

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-

``````my_list.pop(1)
print(my_list)``````

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 –

``list_2=[1,5,2,90,3]``

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)-

``````list_2.sort()
print(list_2)``````

And here’s the sorted list-

``[1, 2, 3, 5, 90]``

Now, let’s sort the list in reverse order (descending order)-

``````list_2.sort(reverse=True)
print(list_2)``````

And here’s our list in descending order-

``[90, 5, 3, 2, 1]``

### 4. reverse()→

The reverse method is used to reverse a list. Let’s try this method on the final form of my_list.

``````my_list.reverse()
print(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.

Related Posts:

Online Compilers