In this tutorial, we will delve into one of Python’s built-in methods known as pop()
. This method is used to remove an item from a list or dictionary and also gives us the option to return it. Let’s explore how it works.
Usage in Lists
The syntax for using the pop() method in lists is: list.pop(index)
.
# Example
my_list = ['apple', 'banana', 'cherry']
my_list.pop(1)
print(my_list) # Output: ['apple', 'cherry']
In this example, we removed the item at index 1 (‘banana’) from our list. If no index is specified, the pop() method removes and returns the last item in the list.
Usage in Dictionaries
The syntax for using the pop() method with dictionaries is slightly different: dict.pop(key[, default])
.
# Example
my_dict = {'name': 'John', 'age': 30}
my_dict.pop('age')
print(my_dict) # Output: {'name': 'John'}
In this case, we removed the key-value pair with key ‘age’. If you try to remove a key that does not exist without providing a default value, Python raises a KeyError.
Providing a Default Value
You can avoid KeyError by providing a default value that will be returned if the key does not exist:
# Example
my_dict = {'name': 'John', 'age': 30}
age = my_dict.pop('height', 'Key not found')
print(age) # Output: 'Key not found'
In this example, since ‘height’ does not exist in our dictionary, the pop() method returns the string ‘Key not found’.
Conclusion
The Python pop()
method is a versatile tool that can be used to manipulate and retrieve data from lists and dictionaries. Its usage varies slightly between these two data types, but understanding how it works will greatly enhance your ability to work with Python collections.
We hope you find this tutorial helpful. Happy coding!