Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Set remove()

#1
Python Set remove()

Python’s set.remove(x) method removes an element x from this set if it is a member, otherwise it raises a KeyError.

Here’s a minimal example where you remove the string element 'Bob' from the set by means of the s.remove() method:

>>> s = {'Alice', 'Bob', 'Cloe'}
>>> s.remove('Bob')
>>> s
{'Alice', 'Cloe'}


Syntax


Let’s dive into the formal syntax of the set.remove() method.

set.remove(element)

Argument Data Type Explanation
element hashable object Element to be removed from the set.

Return Value of Set remove()


The return value of set.remove() is None.

set.discard() vs set.remove()


The set.discard() method is similar to the set.remove() method. Both methods take an element to be removed as an argument and remove this element from the set on which they’re called. If the element to be removed exists in the set, the methods have the same behavior.

? The difference between set.discard() and set.remove() is that set.discard() doesn’t raise an error whereas set.remove() raises a KeyError if the element to be removed is not a member of the set.

As a result, nothing bad happens if you discard the same element twice:

>>> s = {'Alice', 'Bob', 'Cloe'}
>>> s.discard('Bob')
>>> s.discard('Bob')
>>> s
{'Alice', 'Cloe'}

However, if you remove the same element twice, Python raises a KeyError as soon as the element is not a member of the set anymore:

>>> s = {'Alice', 'Bob', 'Cloe'}
>>> s.remove('Bob')
>>> s.remove('Bob')
Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> s.remove('Bob')
KeyError: 'Bob'

In most instances, you don’t want this behavior which is why I recommend you use the discard() method per default to remove elements from the set rather than implementing a more complicated try/except logic to handle the error.

Python Set Remove If Exists


To remove an element x from a set if it exists, use the set.discard(x), not the set.remove(x) method. In contrast to set.remove(x), the method set.discard(x) doesn’t raise a KeyError if the element doesn’t exist.

>>> s = {'Alice', 'Bob', 'Liz'} # Element exists:
>>> s.discard('Alice') # Element doesn't exist:
>>> s.discard('Alice')
>>> s
{'Liz', 'Bob'}

Python Set Remove and Return


To remove an arbitrary element from a set and return the element, use the method s.pop(x).

>>> s = {'Alice', 'Bob', 'Liz'}
>>> s.pop() 'Alice'

Python Set Remove Multiple Elements


Problem Formulation: Given a set and an iterable of elements that you want to remove from the set. But you don’t want Python to raise an error if the set elements are not present. In other words, how to remove multiple elements from the set?

? To remove multiple elements from a set, use the set.difference_update(elements) method. This method removes all elements that are also members of the set. If none of the elements is a member, the method does nothing.

Here’s an example of the set.difference_update() method to remove multiple elements:

>>> s = {1, 2, 3, 'Alice', 'Bob', 'Carl'}
>>> to_remove = {1, 'Alice', 'Bob'}
>>> s.difference_update(to_remove)
>>> s
{2, 3, 'Carl'}

I find this method superior to looping over all elements to be removed because it’s more concise:

>>> s = {1, 2, 3, 'Alice', 'Bob', 'Carl'}
>>> to_remove = {1, 'Alice', 'Bob'}
>>> for element in to_remove: s.discard(element) >>> s
{2, 3, 'Carl'}

What is the Time Complexity of set.remove()?


The runtime complexity of the set.remove() function on a set with n elements is O(1). So, Python’s set.remove() method has constant runtime complexity. The reason is that set membership has constant runtime complexity due to the hash table implementation—and given the element in question, we can easily remove it from the set without looking at all elements in the set.

You can see this in the following simple experiment where we run the set method multiple times for an increasing number of set elements.

What is the Time Complexity of Set remove()?
Figure: The runtime (y-axis) is independent of the number of set elements (x-axis), so set.remove() has constant runtime complexity.

I ran this experiment on my Acer Aspire 5 notebook (I know) with Intel Core i7 (8th Gen) processor and 16GB of memory. Here’s the code of the experiment:

import matplotlib.pyplot as plt
import time sizes = [i * 10**5 for i in range(50)]
runtimes = [] for size in sizes: s = set(range(size)) # Start track time ... t1 = time.time() s.remove(size-99) t2 = time.time() # ... end track time runtimes.append(t2-t1) plt.plot(sizes, runtimes)
plt.ylabel('Runtime (s)')
plt.xlabel('Set Size') plt.show()

Other Python Set Methods


All set methods are called on a given set. For example, if you created a set s = {1, 2, 3}, you’d call s.clear() to remove all elements of the set. We use the term “this set” to refer to the set on which the method is executed.


add() Add an element to this set
clear() Remove all elements from this set
copy() Create and return a flat copy of this set
difference() Create and return a new set containing all elements of this set except the ones in the given set arguments. The resulting set has at most as many elements as any other.
difference_update() Remove all elements from this set that are members of any of the given set arguments.
discard() Remove an element from this set if it is a member, otherwise do nothing.
intersection() Create and return a new set that contains all elements that are members of all sets: this and the specified as well. .
intersection_update() Removes all elements from this set that are not members in all other specified sets.
isdisjoint() Return True if no element from this set is a member of any other specified set. Sets are disjoint if and only if their intersection is the empty set.
issubset() Return True if all elements of this set are members of the specified set argument.
issuperset() Return True if all elements of the specified set argument are members of this set.
pop() Remove and return a random element from this set. If the set is empty, it’ll raise a KeyError.
remove() Remove and return a specific element from this set as defined in the argument. If the set doesn’t contain the element, it’ll raise a KeyError.
symmetric_difference() Return a new set with elements in either this set or the specified set argument, but not elements that are members of both.
symmetric_difference_update() Replace this set with the symmetric difference, i.e., elements in either this set or the specified set argument, but not elements that are members of both.
union() Create and return a new set with all elements that are in this set, or in any of the specified set arguments.
update() Update this set with all elements that are in this set, or in any of the specified set arguments. The resulting set has at least as many elements as any other.

The post Python Set remove() first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...et-remove/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How To Remove All Non-Alphabet Characters From A String? xSicKxBot 0 34 04-17-2021, 09:56 PM
Last Post: xSicKxBot
  [Tut] How to Remove Everything After the Last Character in a String? xSicKxBot 0 80 02-02-2021, 08:23 AM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 99 12-19-2020, 02:05 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 161 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] Hello World! A Python One-Liner to Get Started with Python Quickly xSicKxBot 0 141 09-07-2020, 06:10 PM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Remove Multiple Items From a List xSicKxBot 0 232 06-29-2020, 04:37 AM
Last Post: xSicKxBot
  [Tut] How to Combine Two Python Lists and Remove Duplicates in Second List? xSicKxBot 0 196 06-11-2020, 07:30 AM
Last Post: xSicKxBot
  [Tut] Python Join List of Bytes (and What’s a Python Byte Anyway?) xSicKxBot 0 215 06-10-2020, 05:38 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List of Lists? xSicKxBot 0 249 05-05-2020, 11:27 PM
Last Post: xSicKxBot
  [Tut] How to Remove Empty Lists from a List of Lists in Python? xSicKxBot 0 214 05-02-2020, 10:54 PM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
(Indie Deal) God Eater 3, DRAGON BALL, T...
Last Post: xSicKxBot
Today 10:20 AM
» Replies: 0
» Views: 6
Microsoft - Making remote and hybrid mee...
Last Post: xSicKxBot
Today 05:33 AM
» Replies: 0
» Views: 7
News - JAVA EDITION: SNAPSHOT 21W19A
Last Post: xSicKxBot
Today 05:31 AM
» Replies: 0
» Views: 7
News - Koei Tecmo’s Guzzler Joins Hamste...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 8
News - Sega Looking To Release Brand New...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
Xbox Wire - Xbox Spotlight: Mental Healt...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
News - Live services push EA to $6.19 bi...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 43
News - Blog: Improving the ‘About This G...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 36
[Tut] How to Check the Pandas Version in...
Last Post: xSicKxBot
Yesterday 08:38 PM
» Replies: 0
» Views: 8
(Indie Deal) NBA 2K21, MY HERO ONE'S JUS...
Last Post: xSicKxBot
Yesterday 08:37 PM
» Replies: 0
» Views: 6

[-]
Twitter

Copyright © SickGaming.net 2012-2020