I want to print every number and index:
nums = [3,2,1,5,6,4]
#1st code:
for i in range(len(nums)):
print(i,nums[i])
#2nd code:
length = len(nums)
for i in range(length):
print(i,nums[i])
Out of these two codes which one is efficient or are they same?
>Solution :
Both examples will result in the same byte code, except for the fact that the second option also stores the length in a separate variable. So both are effectively identical and there will be no noticeable impact from using one over the other.
The reason for this is btw. that the iteration target, i.e. range(len(nums)) or range(length) is only executed once at the beginning of your loop. So that code never runs more than once, so it doesn’t matter whether you execute that code outside of the for loop syntax, or within.