Accessing the Index in 'For' Loops

Accessing the index in 'for' loops

Use the built-in function enumerate():

for idx, x in enumerate(xs):
print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

Check out PEP 279 for more.

How do you get the index of the current iteration of a foreach loop?

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index

How to get index in a loop in R

You can do something like this, which is literally getting the i value.

names <- c("name1", "name2")
i<-0
for(name in names){
i<-i+1
print(i)

}

Or change the loop to use a numeric index

names <- c("name1", "name2")
for(i in 1:length(names)){
print(i)

}

Or use the which function.

names <- c("name1", "name2")
for(name in names){

print(which(name == names))

}

How to increment index in Python loop

By using list comprehension you can do this in a one-liner

s = 'teststring'

r = ' '.join([s[i:i+2] for i in range(len(s)-1)])

print(r)

Indexing the variable in a for loop Python

If using numpy with a multi-dimensional array, you can use itertools.product to iterate across all dimensions of the array.

import numpy as np

L = np.zeros((theta, gamma, N))
for i,j,k in itertools.product(range(theta),range(gamma),range(N)):
L[i,j,k] = (gamma[j]*math.pi)*((theta[i])**2) + x[n]

Accessing a value by index in enumerate for-loop

If you want to simply access the column's element from its index, you can simply do and or try this:

for i, f in enumerate(df['col1']):
if df['col1'][i] < df['col1'][i - 1]:
# do something you desire

Tell me if it works.



Related Topics



Leave a reply



Submit