Python Language Set

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • empty_set = set() # initialize an empty set
  • literal_set = {'foo', 'bar', 'baz'} # construct a set with 3 strings inside it
  • set_from_list = set(['foo', 'bar', 'baz']) # call the set function for a new set
  • set_from_iter = set(x for x in range(30)) # use arbitrary iterables to create a set
  • set_from_iter = {x for x in [random.randint(0,10) for i in range(10)]} # alternative notation

Remarks

Sets are unordered and have very fast lookup time (amortized O(1) if you want to get technical). It is great to use when you have a collection of things, the order doesn't matter, and you'll be looking up items by name a lot. If it makes more sense to look up items by an index number, consider using a list instead. If order matters, consider a list as well.

Sets are mutable and thus cannot be hashed, so you cannot use them as dictionary keys or put them in other sets, or anywhere else that requires hashable types. In such cases, you can use an immutable frozenset.

The elements of a set must be hashable. This means that they have a correct __hash__ method, that is consistent with __eq__. In general, mutable types such as list or set are not hashable and cannot be put in a set. If you encounter this problem, consider using dict and immutable keys.



Got any Python Language Question?