performance - Will "for i in sorted(my_list):" sort the list every time? -
let's have list my_list
bunch of numbers, in random order.
i want print these numbers, sorted. if do:
for in sorted(my_list): print(i)
does mean list re-sorted @ every iteration? there advantage/disadvantage on more verbose
sorted_list = sorted(my_list) in sorted_list: print(i)
?
no, list not sorted on every iteration because sorted()
creates new list, , loop iterate on that.
of course, if plan on looping on sorted list multiple times, makes sense store in variable.
Comments
Post a Comment