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