-4

Hello I'm beginner in Python and trying to read a part of a code with for loop but can't understand it, does any body knows how there is index over loop counter? Thanks

updateNodeNbrs = []
for a in nodeData:
    updateNodeNbrs.append(a[0])
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • 1
    What is `nodeData`? – Daniil Ryzhkov Aug 18 '16 at 12:00
  • `a` is not a loop counter in the classical sense like `(0,1,2,...)`. It iterates through the values of `nodeData` instead and if those are in turn containers, you can index them. Try printing `a` in the loop to see the values it takes in each iteration. – Ma0 Aug 18 '16 at 12:01
  • If you're use to Javascript for instance - you can think of Python's for-loop as a `for var of...` instead of a `for var in`... – Jon Clements Aug 18 '16 at 12:02

2 Answers2

2

You're iterating directly over the elements of nodeData, so there is no need for an index. The current element is designated by a.

This is equivalent to:

updateNodeNbrs = []
for i in range(len(nodeData)):
    updateNodeNbrs.append(nodeData[i][0])

Although the original code is more pythonic.


If you wanted to make the index appear, you could transform the code with enumerate to:

updateNodeNbrs = []
for i, a in enumerate(nodeData):
    updateNodeNbrs.append(a[0])

And here, i would be the index of element a, and you could use it in the loop.

Community
  • 1
  • 1
AdrienW
  • 3,092
  • 6
  • 29
  • 59
0

See same question here

If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example

l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
   print "index", i, "is", fruit
Community
  • 1
  • 1
Shaig Khaligli
  • 4,955
  • 5
  • 22
  • 32