Home > Mobile >  what is the difference between Loop Through a List & Loop Through the Index Numbers?
what is the difference between Loop Through a List & Loop Through the Index Numbers?

Time:10-23

I found a tutorial of Python Loop List link - https://www.w3schools.com/python/python_lists_loop.asp

The output of both the "Loop Through a List" example and "Loop Through the Index Numbers" are the same. I just wanted to know the actual difference. it would be great, if anyone could help me out. Here are the 2 code examples (if someone doesn't want to click the link)

  • example 1 (Loop Through a List):

    thislist = ["apple", "banana", "cherry"]
    for x in thislist:
      print(x)
    
  • example 2 (Loop Through the Index Numbers):

    thislist = ["apple", "banana", "cherry"]
    for i in range(len(thislist)):
      print(thislist[i])
    

Thank you! I'm a beginner so don't abuse me :).

CodePudding user response:

From the practical point of view the difference is that from the 1st example, you get an object from the list (ex. x == "apple"). This is useful in many cases, that you need to get some information from all the items or you want to make specific changes to all of them.

However, 2nd example you gain the index by which you are able to change (ex. replace) the item in the array with or index another array. Checking if some elements on specific index match with other array on the same index is impossible (or inpractical) done with the 1st example.

CodePudding user response:

In the first example you are looping through the the elements in the list. If all you need is the items in the list, use this.

In the second example you are looping through an iterable representing the indices and using that to index the list. If you need a hold of the current index, use this. Or more concisely

thislist = ["apple", "banana", "cherry"]
for i, x in enumerate(thislist):
  print(i) # index
  print(x)
  • Related