Python set remove value

4 methods to Remove element from Python Set

In this article, we are going to learn about 4 methods to Remove element from Python Set, all are in-built methods of Python Set to Remove elements (remove, discard, pop, clear). If you are wondering, how to delete elements from the python Set here is the answer. You can use the Built-in functions to do this job. We will cover these functions in this article, so you know, what to do to delete elements from a set.

These are the Set inbuilt function of the set to remove elements from the Set.

  • Remove(): Remove an element from Set.
  • Discard(): Remove an element from Set
  • POP(): Remove an arbitrary(random) element
  • Clear() :Remove all elemnts
Читайте также:  Typescript generate random string

1. Python Set Remove()

It removes the given element from the Set. If a passed element does not exist in Set, It raises a KeyError.

Syntax

Parameter

Return Value

  • It removes the given element from the Set and updates the set. It returns None (nothing).

How to Remove element From Python Set using Remove()

In those code examples, we are removing elements from the set using the remove method. just like delete we can add single or mutiple elements to set

first_set = #removing element using remove() method first_set.remove(5) print('set after removing element :',first_set)
Traceback (most recent call last): File "main.py", line 5, in first_set.remove(10) KeyError: 10

2. Set Discard() to Remove element from Python Set

The set. discard() removes the given element from the set. If an element does not exist it will not raise an error. Instead of remove(), we can use this to avoid an error.

Syntax

Parameters

Return Values

It returns None and removes the given element from the SET and updates the Set.

Example: Remove an element From Set using Discard()

In this python program, we have removed the element 6 from the python set just passing the element 6 as a parameter to discard() method

fruit_Set = #removing element using discard() method fruit_Set.discard(6) print('set after removing element :',fruit_Set)

set after removing element :

Code Example: Remove not exist Element

In this python program example, we are removing the element that does not exist in Set using the discard() method. The Set. Discard() method does not throw any exception.

fruit_Set = #removing not exist element using discard() method print(fruit_Set.discard(8)) print('set after removing element :',fruit_Set)

None set after removing element :

3. Python Set Pop()

It removes an arbitrary(random) element from the Set and returns deleted element. It does not take any argument.

Syntax

Parameter

Return Value

It returned an arbitrary deleted element from the set and update the set. The element no longer exists in SET.

Note: If the set is empty, it raises TypeError Exception.

Example: How to Remove an element from Python with Pop()

The Pop() remove element 5,because it choose randomly.

fruit_Set = #removing element using pop() method print('deleted element : ',fruit_Set.pop()) print('set after removing element :',fruit_Set)

Note: The output might be different because Pop() deletes the arbitrary ( random) element.

deleted element : 5 set after removing element :

4. Set Clear()

The clear() in-built method of set removes all elements of the Set. It does not take any argument.

Syntax

Parameters

Return value

Example: Remove all elements of Set using the Clear() method

We are checking the value return by clear() method, as we can see it is returning None. The Set is empty after using the clear() method.

fruit_Set = #removing all elements of the set using the clear() set method print(' value return by clear method : ',fruit_Set.clear()) print('set after clear elements :',fruit_Set)
value return by clear method : None set after clear elements : set()

Источник

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.

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:

Источник

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