Get list from set in python

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

I need to do this because I need to save the collection in the Google App Engine and Entity properties, which may be lists, but not set. I know that I can just iterate over all this, but it looks like it should be a short or β€œbest” way to do it.

+42
python list set
Jun 19 2018-11-22T00:
source share
3 answers
 >>> s = set([1, 2, 3]) >>> list(s) [1, 2, 3] 

Please note that the list you receive does not have a specific order.

+53
Jun 19 2018-11-22T00:
source share

See Sven's answer, but instead I would use the sorted() function: this way you will get the elements in a good predictable order (for example, you can compare the lists later).

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

Of course, set items must be sortable in order for this to work. You cannot sort complex numbers (see gnibbler Comment). In Python 3, you also cannot sort any set with mixed data types, for example. set([1, 2, 'string']) .

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

+53
Jun 19 2018-11-11T00:
source share
 >>> a = [1, 2, 3, 4, 2, 3] >>> b = set(a) >>> b set([1, 2, 3, 4]) >>> c = list(b) >>> c [1, 2, 3, 4] >>> 
+2
Jun 20 '11 at 10:27
source share



All Articles