Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does using "for i in range(len(nums))" calculate length of nums for every iteration?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading