Python set safe remove

Python Remove Set Element If Exists

Here are the two ways to remove an element of a set if it exists in Python:

Method 1: Using the Set.discard() method

To remove an element from Set if it exists in Python, you can use the “Set.discard()” method. The Set.discard() method is “used to remove an element from the Set only if an element is present”. If an element is not present in the Set, it does not throw any error or exception and prints the Set as it is.

Example

data_set = data_set.discard(19) print(data_set)

In this example, we removed element “19” from the Set. Since it exists in the Set, the discard() method removes it.

Removing an element if it does not exist

If an element does not exist in the Set and try to remove that element using the discard() method, the original Set is unaffected. Therefore, no errors or exceptions will be raised.

data_set = data_set.discard(20) print(data_set)

You can see that we get the same Set without any modifications.

Method 2: Using the Set.remove() method

The Set.remove() method is “used to remove an element if it is present in the Set”. It will throw an error if an element does not exist in the Set.

data_set = data_set.remove(21) print(data_set)

The “21” element exists in the Set. That’s why it was removed from the Set.

Removing an element if it does not exist

If we try to remove an element that does not exist in the Set, we will get KeyError.

data_set = data_set.remove(10) print(data_set)

To prevent KeyError in our example, use the discard() method instead of the remove() method.

Difference between Set remove() and Set discard()

remove() discard()
Definition The remove() method removes the specified element from the set. The discard() method removes the specified element from the set if it is present.
Parameters This method takes one argument: the element to be removed. This method takes one argument: the element to be removed.
Behavior If the element is not found in the set, the remove() method raises a KeyError. If the element is not found in the set, discard() does nothing and does not raise an error.
Return Value This method does not return any value. It modifies the set in place. This method does not return any value. It modifies the set in place.
Читайте также:  Connection provider in java

Источник

How to Remove Items from Python Sets

How to Remove Items from a Python Set Cover Image

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.

Читайте также:  Message переменная python значение

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.

Читайте также:  Построение графика функции python turtle

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:

Источник

Оцените статью