How to get a list from a set?

PythonListSet

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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.

Solution 3 - Python

>>> a = [1, 2, 3, 4, 2, 3]
>>> b = set(a)
>>> b
set([1, 2, 3, 4])
>>> c = list(b)
>>> c
[1, 2, 3, 4]
>>> 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris DutrowView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonPetr ViktorinView Answer on Stackoverflow
Solution 3 - PythonsamView Answer on Stackoverflow