- Python Set pop() method
- 1. Quick Examples of Set pop()
- 2. Set pop() Method in Python
- 2.1 Set pop() Syntax
- 3. Examples
- .lpubn
- 5. Conclusion
- You may also like reading:
- How to Remove Items from Python Sets
- A Quick Primer on Python Sets
- Remove an Item from a Python Set with remove
- Remove an Item Safely from a Python Set with discard
- Remove and Return a Random Item from a Python Set with pop
- Remove Multiple Items from a Python Set with difference_update
- Remove All Items from a Python Set
- Remove Items from a Python Set Conditionally
- Conclusion
- Additional Resources
Python Set pop() method
The Python Set pop() method is used to get a random arbitrary element from the set and the value returned will be removed from the input set. If the set is empty, it raises a KeyError .
Note that set.pop() is a mutating operation, which means that it modifies the original set in place. If you want to remove an element from a set without modifying the set, you can use the set.discard() method instead.
1. Quick Examples of Set pop()
Following are quick examples of how to use pop() method in python.
# Quick Examples # Example 1: Use pop() to remove any element myset = print("Actual set:",myset) popped=myset.pop() print("Popped item: ",popped) print("Final set:",myset) # Example 2: Use pop() to remove any element myset = print("Actual set:",myset) popped=myset.pop() print("Popped item: ",popped) print("Final set:",myset) # Example 3: Pop an element from an empty set s = set() try: s.pop() except KeyError: print("The set is empty")
2. Set pop() Method in Python
In Python, the set.pop() method removes and returns an arbitrary element from the set. If the set is empty, TypeError is thrown. So make sure that set contains at least one element to pop. It will not take any parameters.
Keep in mind that set.pop() is a mutating operation, which means that it modifies the set in place. If you want to remove an element from a set without modifying the set, you can use the set.discard() method instead.
2.1 Set pop() Syntax
# Here, myset is the input set. myset.pop()
3. Examples
Let’s create a set with some integers and use pop() method to remove one element randomly.
# Consider the set with some integers myset = print("Actual set:",myset) # Use pop() to remove any element popped=myset.pop() print("Popped item: ",popped) print("Final set:",myset) # Output: # Actual set: # Popped item: 1 # Final set:
The above example removes an element 1 from the set and this element has been removed from the original set.
Let’s create a set with some strings and use the pop() method to remove one element randomly. Here, it removes the element pandas from the set.
# Consider the set with some strings myset = print("Actual set:",myset) # Use pop() to remove any element popped=myset.pop() print("Popped item: ",popped) print("Final set:",myset) # Output: # Actual set: # Popped item: panda # Final set:
.lpubn
Let’s create an empty set and try to remove the item using pop(). As specified above calling pop() on empty Set returns an error.
# Consider an empty set myset = <> print("Actual set:",myset) # Pop element popped=myset.pop() print("Popped item: ",popped)
If you don’t want to throw an error, use the below approach. Here, we are using try except to catch KeyError and print the message.
# Pop an element from an empty set s = set() try: s.pop() except KeyError: print("The set is empty") # Output: # The set is empty
5. Conclusion
pop() in python Set is used to remove a random element from the set. If the set is empty, TypeError is thrown. So make sure that set contains at least one element to pop or at least use exception handling to catch the error.
You may also like reading:
How to Remove Items from Python Sets
In this tutorial, you’ll learn how to remove items from a Python set. You’ll learn how to remove items using the remove method, the discard method, the pop method, and the difference_update method. You’ll learn the differences between each of these methods and when you may want to use which. You’ll also learn how to remove items from sets conditionally, such as all numbers below a threshold.
The Quick Answer: Use discard to Remove an Item from a Set in Python
# Remove an Item Safely from a Python Set numbers = numbers.discard(2) print(numbers) # Returns:
A Quick Primer on Python Sets
Sets are a unique container data structure in Python. Sets are created by using comma-separated values between curly braces <> .
Sets have the following main attributes:
- Unordered: meaning that we can’t access items based on their index
- Unique: meaning that an item can only exist once
- Mutable: meaning that the set itself can be changed (while sets must contain immutable items themselves)
Python sets also provide a number of helpful methods, such as being able to calculate differences between sets.
We can create an empty set by using the set() function. Let’s see what this looks like:
# Creating empty sets set1 = set()
We need to be careful to not simply create an empty set with curly braces. This will return a dictionary instead. In order to create a set using only curly braces, it must contain at least one item.
Remove an Item from a Python Set with remove
Python sets come with a method, remove , that lets us remove an item from a set. The method accepts a single argument: the item we want to remove.
Let’s take a look at how we can use the method:
# Remove an Item from a Python Set using .remove() numbers = numbers.remove(2) print(numbers) # Returns:
We can see that by passing in the value of 2 that it was successfully removed from our set. The operation took occurred in-place, meaning that we didn’t need to re-assign the set.
Something to note, however, is that if we try to remove an item that doesn’t exist, Python will raise a KeyError . Let’s see what this looks like:
# Raising an Error When an Item Doesn't Exist numbers = numbers.remove(6) # Raises KeyError: 6
In order to prevent the error from ending our program, we need to be able to handle this exception. We can either first check if any item exists in a set, or we can use a try-except statement. Let’s see how this works:
# Preventing a Program from Crashing with set.remove() numbers = try: numbers.remove(6) except KeyError: pass
Typing try-except statements can be a little tedious. Because of this, we can use the discard method to safely remove an item from a Python set.
Remove an Item Safely from a Python Set with discard
In the above section, you learned about the Python set.remove() method. The set.discard() method accomplishes the same thing – though it handles missing keys without throwing an exception. If an item that doesn’t exist is passed into the method, the method will simply return None.
# Remove an Item from a Python Set using .discard() numbers = numbers.discard(2) print(numbers) # Returns:
We can see in the first use of discard that we were able to drop an item successfully.
Now, let’s try using the discard method to remove an item that doesn’t exist:
# Safely handle removing items that don't exist numbers = numbers.discard(6) print(numbers) # Returns:
We can see here that when we attempted to remove an item that didn’t exist using the set.discard() method, nothing happened.
In the next section, you’ll learn how to use the set.pop() method to remove an item and return it.
Remove and Return a Random Item from a Python Set with pop
The Python set.pop() method removes a random item from a set and returns it. This has many potential applications, such as in game development. Not only does it remove an item, but it also returns it meaning that you can assign it to a variable. For example, in a card game where each item only exists once, this could be used to draw a card.
Let’s see how this method works to delete an item from a set:
# Remove an Item from a Python Set using .pop() numbers = number = numbers.pop() print('number: ', number) print('numbers: ', numbers) # Returns: # number: 1 # numbers:
We can see that when we pop a value from a set, the value is both returned and removed from the set.
What happens when we try to apply the .pop() method to an empty set? For example, if we had drawn all the cards from our set of cards?
# Popping an empty set numbers = for _ in range(6): numbers.pop() print(numbers) # Returns: # # # # # set() # KeyError: 'pop from an empty set'
In the code above, we pop an item from a set and print the remaining items six times. After the fifth time, the set is empty. When we attempt to pop an item from an empty set, a KeyError is raised.
In the next section, you’ll learn how to remove multiple items from a Python set.
Remove Multiple Items from a Python Set with difference_update
There may be many times when you don’t simply want to remove a single item from a set, but rather want to remove multiple items. One way to accomplish this is to use a for loop to iterate over a list of items to remove and apply the .discard() method. Let’s see what this might look like:
# Deleting multiple items from a set using a for loop numbers = numbers_to_remove = [1, 3, 5] for number in numbers_to_remove: numbers.discard(number) print(numbers) # Returns:
While this approach works, there is actually a much simpler way to accomplish this. That is by using the .difference_update() method. The method accepts an iterable, such as a list, and removes all the items from the set.
Let’s convert our for loop approach to using the .difference_update() method:
# Deleting multiple items from a set using .difference_update() numbers = numbers_to_remove = [1, 3, 5] numbers.difference_update(numbers_to_remove) print(numbers) # Returns:
We can see that by applying the .difference_update() method, that we were able to easily delete multiple items from a set. What’s even more is that the method does this in a safe manner. If we passed in an item that didn’t exist, the method would not raise an error.
Remove All Items from a Python Set
Python provides an easy method to remove all items from a set as well. This method, .clear() , clears out all the items from a set and returns an empty set.
Let’s see how this method works:
# Delete all items from a Python set numbers = numbers.clear() print(numbers) # Returns: set()
In the next section, you’ll learn how to delete items from a set based on a condition.
Remove Items from a Python Set Conditionally
In this final section, you’ll learn how to remove items from a set based on a condition. First, you’ll learn how to do this using a for loop and the .discard() method and later with a set comprehension.
Let’s take a set of numbers and delete all items that are even using a for loop:
# Removing items conditionally from a set numbers = for number in list(numbers): if number % 2 == 0: numbers.discard(number) print(numbers) # Returns:
The important thing to note here is that we need to iterate over the items in the set after we convert it to a list. If we don’t do this, we encounter a RuntimeError .
We can also accomplish this using a Python set comprehension. These work very similar to Python list comprehensions and we can use them to easily filter our sets.
# Removing items conditionally from a set numbers = numbers = print(numbers) # Returns:
We can see that this approach is quite a bit shorter and a lot more readable. It can also be intimidating to newcomers to the language, so use whichever approach is easier for you to be able to understand in the future.
Conclusion
In this tutorial, you learned how to use Python to remove items from a set. You learned how to use the .pop() and .discard() methods. You also learned how to remove multiple items or all items from a set. Finally, you learned how to remove items conditionally from a set.
Additional Resources
To learn more about related topics, check out these tutorials here: