57
votes

Ho 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.

3
@Franklin I am tempted to close as general reference chat.meta.stackoverflow.com/transcript/message/654451#654451 - Trufa
@Franklin: I searched in general search and then I posted variants of the subject line in Stackoverflow to make sure it wasn't a dupe. This is the kind of information that should be represented here on Stackoverflow.com - Chris Dutrow
@Franklin: I don't think this one is really easy to find with Google. Searches like "python set list" or similar will return more general documentation - Sven Marnach
@Sven Marnach In the first 10 google results there are 2 links that would help you if you try it in the interactive console: ircarchive.info/python/2007/5/8/76.html and daniweb.com/software-development/python/threads/93829 but I think this is an edge case, since the documentation is not really authoritative and not "very" easily accessible. - Trufa
@Sven Marnach: Yeah, especially if you're just learning python. The first place you'll look is the methods associated with "set" such as "add()" and "update()". You will be frustrated when there is nothing available like "get_list" or "get_iterable" and then you won't know where to look next. - Chris Dutrow

3 Answers

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

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

71
votes

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.

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