I have the following code:
list1 = [4,1,2,6]
for elem in sorted(list1):
#some task
I was wondering how many times does Python sort the
In both code examples, the list is sorted only once.
The expression on the right of the in
operator in a for-loop header is evaluated just once, before looping commences. You can read about this in the documentation:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]The expression list is evaluated once; it should yield an iterable object.
In fact, the second code example is less efficient because there is an unnecessary assignment.