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