Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list from a set in python

Tags:

python

list

set

How do I get the contents of a set() in list[] form in Python?

I need to do this because I need to save the collection in Google App Engine and Entity property types can be lists, but not sets. I know I can just iterate over the whole thing, but it seems like there should be a short-cut, or "best practice" way to do this.

like image 707
Chris Dutrow Avatar asked Jun 19 '11 22:06

Chris Dutrow


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.

How do you create a list from a set in Python?

You can use python set() function to convert list to set.It is simplest way to convert list to set. As Set does not allow duplicates, when you convert list to set, all duplicates will be removed in the set. Let's understand with the help of example.

How do I get an element from a set in Python?

You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.


2 Answers

>>> s = set([1, 2, 3]) >>> list(s) [1, 2, 3] 

Note that the list you get doesn't have a defined order.

like image 115
Sven Marnach Avatar answered Sep 17 '22 08:09

Sven Marnach


See Sven's answer, but I would use the sorted() function instead: that way you get the elements in a nice predictable order (so you can compare the lists afterwards, for example).

>>> s = set([1, 2, 3, 4, 5]) >>> sorted(s) [1, 2, 3, 4, 5] 

Of course, the set elements have to be sortable for this to work. You can't sort complex numbers (see gnibbler's comment). In Python 3, you also can't sort any set with mixed data types, e.g. set([1, 2, 'string']).

You can use sorted(s, key=str), but it may not be worth the trouble in these cases.

like image 28
Petr Viktorin Avatar answered Sep 21 '22 08:09

Petr Viktorin