Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python set to list

Tags:

python

list

set

People also ask

Can you convert a set to a list in Python?

Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.

Can set be converted to list?

List Constructor with Set argument. The most straightforward way to convert a set to a list is by passing the set as an argument while creating the list. This calls the constructor and from there onwards the constructor takes care of the rest. Since the set has been converted to a list, the elements are now ordered.

How do you add a set to a list in Python?

To add a list to set in Python, use the set. update() function. The set. update() is a built-in Python function that accepts a single element or multiple iterable sequences as arguments and adds that to the set.


Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):

>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']

Check that you didn't overwrite list by accident:

>>> assert list == __builtins__.list

You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error

>>> set=set()
>>> set=set()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.

Here is a less confusing version using different names for each variable. Using a fresh interpreter

>>> a=set()
>>> b=a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

Hopefully it is obvious that calling a is an error


before you write set(XXXXX) you have used "set" as a variable e.g.

set = 90 #you have used "set" as an object
…
…
a = set(["Blah", "Hello"])
a = list(a)

This will work:

>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]

However, if you have used "list" or "set" as a variable name you will get the:

TypeError: 'set' object is not callable

eg:

>>> set = [1,1,2,2,3,3,4,5]
>>> print list(set(set))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

Same error will occur if you have used "list" as a variable name.


s = set([1,2,3])
print [ x for x in iter(s) ]