Stats

245 Contributors: 16 Wednesday, August 2, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Set

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.

Related Examples