While learning about map(function, *iterables)
function, I found that it applies the function
with n
number of arguments where n
is the number of supplied iterables
as args to the map()
function. So, I tried and it's working as expected.
Another point is list
s in Python maintain the insertion order while set
s are unordered. Apart from having all these details, I'm unable to understand that -
Why does applying map()
on a set
and then converting the resultant map object to a list
give me a sorted list while applying map()
on a list
and then converting the map object to a list
gives me a list with the same order as it was in the supplied list?
This is my source code:
l1 = [1, 2, 4, 5, 3]
s1 = {6, 7, 9, 8, 0}
print(list(map(lambda num: num * 2, l1)))
print(list(map(lambda num: num * 2, s1)))
and this is the output:
[2, 4, 8, 10, 6]
[0, 12, 14, 16, 18]
In case of:
print(list(map(lambda num: num * 2, s1)))
each time I run the program, I'm getting the same sorted list but if I print(s1)
I'm getting different orders of s1
. Shouldn't I get a list with random order of doubled numbers each time I run the program?
P.S.
Another user, suggested me a possible duplicate order-of-unordered-python-sets. But, if possible, I seek an updated answer for this question that talks about the implementation of set
s in current versions of Python (as of now the current version is 3.10.7).
The order-of-unordered-python-sets definitely gives a base to under the reason behind this problem. But please provide your updated answers here so that it'll be relevant for upcoming years. Otherwise, you can definitely vote to close it.