-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])
3
  • 1
    What is nodeData? Commented Aug 18, 2016 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. Commented Aug 18, 2016 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... Commented Aug 18, 2016 at 12:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.