简体   繁体   中英

which of these for-loops is more efficient/the better way to code the loop

Which is better between these two for-loops in python? I have "assumed" the compiler would be smart enough to do the json.loads just one time and, on its own, store the data in a temporary variable so that it could maintain the iterator needed to process the for-loop. But then I started to wonder if I was mistaken and that the first style would be causing unwarranted extra steps.

for employee in json.loads(response.content)

OR

temp = json.loads(response.content)
   for employee in temp

Although both are essentially the same, there's one good reason to favor a temporary value: it lets you catch any errors in the call to json.loads before trying to iterate over the result. This is consistent with keeping the code in a try statement as focused as possible.

try:
    employees = json.loads(response.content)
except JSONDecodeError:
    # Maybe log an error message
    # Maybe just reraise the exception
    employees = []

for employee in employees:
    ...

It's fairly clear from the documentation :

 for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]

The expression list is evaluated once;

So your worry is unfounded, and the first way is preferable unless you want to reuse the data again or writing it on the for line would make the line too long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM