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

Function range() in Python

I’m trying to understand what is the difference here? Is function range() better to be used here? Or why will we use range() if we cand do simply like (code #2)

Code 1:

a = [1, 2, 3, 4, 5]    
for elem in range(len(a)):   
  print(elem)  

Code 2:

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

a = [1, 2, 3, 4, 5]   
for elem in a:   
    print(elem, end=' ')

>Solution :

Short Answer

Both methods are valid ways to iterate over a list in Python, but they are used in different scenarios.

So the choice between the two methods depends on what you need to do with the list. If you only need the values and not the indices, the second method (for elem in a) is simpler and more idiomatic in Python. If you need the indices, the first method (range(len(a))) is appropriate.

Also as @samwise mentioned in the comments the enumerate function lets you work with both the indices and the values if you wanted.

Additional Details

  1. Using range(len(a)) will give you the index of each element in the list. This is useful when you not only need the value of each element, but also its position in the list. In your example, elem will be the index of each element, not the element itself. You would use this method if you want to manipulate the list in place or if you need to know the index of each element for some reason.

    Code 1:

    a = [1, 2, 3, 4, 5]
    for i in range(len(a)):
        print(i)
    

    This will print the indices (0, 1, 2, 3, 4) not the values of the list.

  2. Using for elem in a will give you each element in the list directly. This is a more Pythonic way to iterate over a list when you don’t need to know the index of each element. In your example, elem will be each element in the list.

    Code 2:

    a = [1, 2, 3, 4, 5]
    for elem in a:
        print(elem, end=' ')
    

    This will print the values (1, 2, 3, 4, 5) of the list.

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