Lesson 12: .pop() method

.pop() method can be used for lists or dictionaries. It will remove the specified item from the list (or dictionary) and it will return the removed item at the same time.

Function 1: .pop()

.pop() method is useful for removing the last element (or an element at a specific index) from a list and on top of that it will return the removed item. (It also works with dictionaries if you pass the key value you’re looking for.)

Used Where?

If you need to remove an element from a list or  a dictionary and if you also need the returned value, .pop() can be very useful. Let’s see some examples. 

Syntax do(s)

1) .pop() method takes the index as an argument.

2) Or if it’s a dictionary .pop() method takes a key as an argument.

Syntax don't(s)

1) If you’re using .pop with a dictionary and your key is a string, don’t forget the quotes.

Example 1

>>> peeps = [“Joe”, “Liam”, “Oleg”]
>>> a = peeps.pop()
>>> print(a)
>>> print(peeps)

Oleg
[“Joe”, “Liam”]

1) You can see in the above example that once the pop() function is called, it removed the last item (“Oleg”) for the list peeps.

2) Also you can see that by assigning this to variable a, we have assigned the returned value (“Oleg”) of .pop() method to the variable a.

3) Finally you can see that there wasn’t any parameters inside the parenthesis of .pop() method. When .pop() method is used this way with empty parenthesis it just aims at the last element.

Tips

1- By typing the index number of the element you’d like to remove and return inside the .pop() method’s parenthesis, you can directly aim that element at that index in a list.

In the next example we will specify the index inside the parenthesis.

Let’s type 0 as the index parameter inside pop method, this will make the method aim at the first element.

Example 2

>>> peeps = [“Joe”, “Liam”, “Oleg”]
>>> a = peeps.pop(0)
>>> print(a)
>>> print(peeps)

Joe
[“Liam”, “Oleg”]

Advanced Concepts (Optional)

You can also use .pop() method with dictionaries.

When using .pop() with dictionaries you have to pass the key you’re looking for inside .pop() method.

Example 3

>>> dict = {“a”:5, “b”: 10, “xyz”: 10101, “c”:15}
removed = dict.pop(“xyz”)
>>> print(dict, “removed: “, removed)

{“a”:5, “b”: 10, “xyz”: 10101, “c”:15} removed: 10101

Exercise 12

Lesson 13

input()

Paul Bennett the calm


Paul Bennett

The Calm

The Calm by Paul Bennett 

“Have you installed Python yet?”

Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.
Sandra Files