Python List pop()

Python list‘s pop method is used to remove and return index(passed parameter).If you do not pass any parameter, then it will remove and return last element of the list.


Syntax

Here list1 is object of the list and index is the index of the element which you want to remove and return.


Return

returns element and remove that element from the list.


Example

Let’s see a very simple example:

countriesList=['India','China','South Africa','Nepal'] #Let's remove and return china from the list country=countriesList.pop(1) print("list Of Counties:",countriesList) print("Country removed from the list:",country)

Output:

list Of Counties: [‘India’, ‘South Africa’, ‘Nepal’]
Country removed from the list: China

As you can see ‘china’ got removed from countriesList.
You can use negative indices too with pop method. When you provide negative indices, it traverse from the end to start of the list.
Let’s understand with the help of example.

listOfCountries=['India','China','Bhutan','USA','Nepal'] country=listOfCountries.pop(-2) print("list Of Counties:",listOfCountries) print("Country removed from the list:",country)

Output:

list Of Counties: [‘India’, ‘China’, ‘Bhutan’, ‘Nepal’]
Country removed from the list: USA

If you do not pass any paramter to pop, it will remove and return last element.

listOfFruits=['Mango','Orange','Banana','Apple','Watermelon'] fruit=listOfFruits.pop() print("list Of Fruits:",listOfFruits) print("Fruit removed from the list:",fruit)

Output:

list Of Fruits: [‘Mango’, ‘Orange’, ‘Banana’, ‘Apple’]
Fruit removed from the list: Watermelon

That’s all about Python List pop() method.

Leave a Reply

Your email address will not be published. Required fields are marked *