Creating a list from a set

Hi Viewer,

I am a newbie to Python and I am learning lists in Python. I see list() accepts an iterable to create a list. But came across the following interesting line of code,

s = {1, 2, 3}
l = list(s)
print(l)
[1, 2, 3]

If my understanding is correct a set is not an iterable type. So how can we create a list from a set? Please clarify.

Thanks.

All built-in collections, including sets, are iterable.

>>> for i in {1,2,3}: print(i)
... 
1
2
3

What if the collection contains tuples?

Edit: I should first ask if a collection can reference tuples?

A tuple is an object like any other, so you can iterate over a collection that contains tuples, and you’ll get those tuples back. And yes, they certainly can.

>>> s = {1, 2, (31, 32, 33, 34), 4, 5}
>>> for i in s: print(i)
... 
1
2
4
5
(31, 32, 33, 34)
1 Like

Ah, thank you for the reply. I know one day it will be as clear to me as it is for you: I’m obsessively determined to up-skill. Currently however, it seems like a common mistake for those near the bottom to attempt to iterate non-iterables (at least it is for me).

1 Like

With that attitude, you definitely will upskill. Keep asking questions! Even the ones you think are dumb questions, because there’s a good chance they’re not :slight_smile:

2 Likes

(Please remember that sets are unordered and so the order of the items when converted to a list may differ, and their order should not be relied on).

1 Like

how can an order differ if there is none :rofl:

I believe the order can differ between runs. But within a run, one can add to and remove from a set. I don’t believe that there is any guarantee that if one restores the original membership, the iteration order will be the same. I am pretty sure that if 2 unequal items have the same hash, their order in iteration may depend on insertion order.

1 Like

(Edit: nvm the discussion was about sets which indeed are unordered, so ignore my response)

Python dictionaries are insertion ordered since Python 3.7.
https://mail.python.org/pipermail/python-dev/2017-December/151283.html

This is a guaranteed language feature and you CAN depend on the order of the dictionary between runs.
Although, even with this guarantee from Python I still act as if dicts are an unordered collection because it just feels weird using dicts as an ordered collection. Also this isn’t the case for most other programming languages so I stick to using them as unordered hash maps.

For some ordered datastructures, you might look over Some datastructures I've worked on

The Red Black Tree in particular, has a set-like variant which is innately sorted.