How many times does a for loop evaluate its expression list?

后端 未结 1 1045
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 06:48

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

相关标签:
1条回答
  • 2020-12-19 07:30

    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.

    0 讨论(0)
提交回复
热议问题