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

1/15/2019 8:14:19 PM

Paolo De Nictolis

5 Answers

New Answer

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

+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])

+5

You're completely right, this functions: nums = range(10) print((list(map(lambda x: x*x, nums))))

+4

You can't eliminate set, or it will return map as an object (try it). With sorted is OK. Thank you very much :)

+2

Of course 'list(map(...' Thanks!