Python map and lambda functions: a sorting problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Python map and lambda functions: a sorting problem

Can someone explain me why the result is ordered till range(6), and unordered from range(7) onwards? nums = list(range(10)) print(set(map(lambda x: x*x, nums)))

15th Jan 2019, 8:14 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 Answers
+ 5
In Python sets don't remember the order of elements. Try using lists instead: print(list(map(lambda x: x*x, nums))) or print(sorted(set(map(lambda x: x*x, nums)))) if you need to delete the duplicates.
15th Jan 2019, 8:51 PM
portpass
+ 6
Paolo De Nictolis I think portpass meant using lists this way: print(list(map(lambda x: x*x, nums))) You could also use a list comprehension: print([x*x for x in nums])
15th Jan 2019, 9:25 PM
Diego
Diego - avatar
+ 5
You're completely right, this functions: nums = range(10) print((list(map(lambda x: x*x, nums))))
15th Jan 2019, 9:30 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 4
You can't eliminate set, or it will return map as an object (try it). With sorted is OK. Thank you very much :)
15th Jan 2019, 9:17 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 2
Of course 'list(map(...' Thanks!
15th Jan 2019, 10:09 PM
portpass