Importing sets in python

When I try to use sets, it shows that there is nothing named set.

from sets import set

> ImportError: cannot import name set

      

How to fix it?

+3


source to share


4 answers


You don't need to import the sets

module
; kits are now built in. Use the built-in set()

type
instead :

>>> set()
set([])

      

You can also use the {1, 2, 3}

set literal syntax :

>>> {1, 2, 3}
set([1, 2, 3])

      



If you want to use a slower module sets

anyway, the object is called Set

with capital S

:

>>> from sets import Set

      

but note that the module is deprecated; using it doesn't add anything over built-in types. The module has been completely removed in Python 3.

+11


source


Use Set

instead Set

because it is a keyword.



from sets import Set

      

0


source


set

need to make amends:

from sets import Set

      

But from Python 2.7 on, set

is built in, and usage sets#Set

is actually quite slower than built in set

.

For example, a coding problem I recently appreciated that looks a lot for small words in dict

or set

takes ~ 3s to work with sets#Set

, but ~ 1.8 with inline set

. This is a significant difference.

0


source


Use 'S' instead of s

 try:
    from sets import Set
 except ImportError:
    Set = set

      

0


source







All Articles