Have a look at enumerate

>>> for i, season in enumerate('Spring Summer Fall Winter'.split(), start=1):
        print i, season
1 Spring
2 Summer
3 Fall
4 Winter
Answer from Fredrik Pihl on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › find current position of list during for loop?
r/learnpython on Reddit: Find current position of list during for loop?
April 3, 2016 -

Hello,

I did this by initializing a counter outside of my loop... e.g.:

list = [1,2,3]
counter = 0
for i in list:
   counter = counter + 1
   if i is 2:
      break

Counter would be 1 here, so doing

print(list[counter]) should return 2.

I was doing this because I was dealing with ~40,000 lists of ~200 length, and finding an element every time near the end. I wanted to print every element before that, so I was starting a counter, reversing the list, and then returning len - counter as the position of that element, then doing print [:element].

Is there some kind of magic variable where I could just do...

for i in list:
   if i is 2:
      return __secret_counter__

?

Discussions

python - How can I access the index value in a 'for' loop? - Stack Overflow
Check out PEP 279 for more. ... Sign up to request clarification or add additional context in comments. ... As Aaron points out below, use start=1 if you want to get 1-5 instead of 0-4. 2018-03-31T22:16:51.887Z+00:00 ... @TheRealChx101 according to my tests (Python 3.6.3) the difference is negligible and sometimes even in favour of enumerate. 2020-02-07T12:18:42.603Z+00:00 ... @TheRealChx101: It's lower than the overhead of looping ... More on stackoverflow.com
🌐 stackoverflow.com
python - what is value and what is position in for loop? - Stack Overflow
Modernizing curation: A proposal for The Workshop and The Archive ... 3 in python what's the relation between the loop variable and the elements in list when we do for loop? More on stackoverflow.com
🌐 stackoverflow.com
Find current position of list during for loop?
Use enumerate() : for count, item in enumerate(stuff): if item == 2: return count Note: Unless you know better, only use is when comparing to None, True, or False. Use == for everything else. I wanted to print every element before that, so I was starting a counter, reversing the list, and then returning len - counter as the position of that element, then doing print [:element]. If you're just trying to find the position of an item in the list, use list.index() : position = stuff.index(2) print(stuff[:position]) More on reddit.com
🌐 r/learnpython
3
4
April 3, 2016
Struggling with Python - can someone explain how ‘for loops’ work in simple terms? 🐍👩‍💻
Say you have a list, my_list = [1, 3, 5, 8] and all you want to do is print it. You would iterate over each item in the list, and print it. So FOR each item, you will print it individually. for item in my_list: print(item) Note that item is a variable assigned when you make the for loop. It could be anything. for x in my_list: print(x) for _ in my_list: print(_) These do the same things. You can also loop through the range using the index for i in range(len(my_list)): print(my_list[i]) Again, i could be anything. It's just the name you are assigning to the current item being iterated. So the basic structure is for thing in bunch_of_things: do_stuff_to(thing) Hope this helps! I am also learning, so someone else may be able to break it down a little better. More on reddit.com
🌐 r/learnpython
85
125
October 29, 2024
🌐
StrataScratch
stratascratch.com › blog › mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - The for loop index refers to the position of the current element in the sequence during each iteration of a for loop. Sometimes, you may want to access the index along with the value of each component while iterating.
🌐
Real Python
realpython.com › python-enumerate
Python enumerate(): Simplify Loops That Need Counters – Real Python
June 23, 2025 - >>> runners = ["Lenka", "Martina", "Gugu"] >>> for position, name in enumerate(runners): ... print(position, name) ... 0 Lenka 1 Martina 2 Gugu · Just like the winner variable earlier, you can name the unpacked loop variables whatever you want. You use position and name in this example, but they could just as easily be named i and value, or any other valid Python names.
Top answer
1 of 16
9261

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.

2 of 16
1371

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

count = 0 # in case items is empty
for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:

So do this:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)
🌐
Real Python
realpython.com › python-for-loop
Python for Loops: The Pythonic Way – Real Python
February 23, 2026 - Note: To learn more about working with enumerate(), check out the Python enumerate(): Simplify Loops That Need Counters tutorial. The enumerate() function also takes an optional argument called start that lets you tweak the initial value. This feature is useful when you need to create counts. Consider the following example that mimics an option menu for a command-line application: Python · >>> def display_menu(options): ... print("Main Menu:") ... for position, option in enumerate(options, start=1): ...
🌐
Enterprise DNA
blog.enterprisedna.co › python-for-loop-index
Python for Loop Index: How to Access It (5 Easy Ways) – Master Data Skills + AI
The loop then prints the index ... before the loop and manually increment within each iteration of the loop. The counter serves as an index to track the position of the current item in the iterable....
Find elsewhere
🌐
Online-python
learn.online-python.com › python › for-loops
Tutorial
fruits = ["apple", "banana", "cherry", "date"] # TODO: Your code here: use enumerate to print each fruit with its position # Expected output: "Fruit 1: apple", "Fruit 2: banana", etc. ... # For Loop Practice - Solution fruits = ["apple", "banana", "cherry", "date"] for index, fruit in enumerate(fruits): print(f"Fruit {index + 1}: {fruit}")
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
Now let’s talk about loops in Python. First we’ll look at two slightly more familiar looping methods and then we’ll look at the idiomatic way to loop in Python. If we wanted to mimic the behavior of our traditional C-style for loop in Python, we could use a while loop:
🌐
Sentry
sentry.io › sentry answers › python › accessing the index in a `for` loop in python
Accessing the Index in a `for` Loop in Python | Sentry
November 22, 2022 - So Python provides a simpler method ... just loop over the elements directly, like so: directions = ['north', 'east', 'south', 'west'] for direction in directions: print(direction)...
🌐
GitHub
hsf-training.github.io › analysis-essentials › python › lists.html
Lists and looping — Analysis essentials documentation
meaning take out 0 elements from the list starting a position 2 and insert the content of the list ``[6]`` in that position. ... Solution You need to slice from the very beginning to the very end of the list. ... This is equivalent to specifying the indices explicitly. ... When you’ve got a collection of things, it’s pretty common to want to access each one sequentially. This is called looping, or iterating, and is super easy. ... We have to indent the code inside the for loop to tell Python that these lines should be run for every iteration.
🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
Learn more about while loops in our Python While Loops Chapter. List Comprehension offers the shortest syntax for looping through lists:
🌐
Python Guides
pythonguides.com › python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - The easiest and most Pythonic way to loop through items with their index is by using the enumerate() function. When you use enumerate(), Python automatically keeps track of the index for you, so you don’t have to manually manage it.
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
4.2. for Statements · 4.3. The range() Function · 4.4. break and continue Statements · 4.5. else Clauses on Loops · 4.6. pass Statements · 4.7. match Statements · 4.8. Defining Functions · 4.9. More on Defining Functions · 4.9.1. Default Argument Values · 4.9.2. Keyword Arguments · 4.9.3. Special parameters · 4.9.3.1. Positional-or-Keyword Arguments ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › loops-in-python
Loops in Python - GeeksforGeeks
The continue statement in Python returns the control to the beginning of the loop. ... for letter in 'geeksforgeeks': if letter == 'e' or letter == 's': continue print('Current Letter :', letter)
Published   2 weeks ago
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to start python for loop at 1
How to Start Python For Loop at 1 - Spark By {Examples}
May 31, 2024 - To start the for loop with index at 1 in Python use the range() with start param at 1 and for the end value use the len() which gives the length of the sequence object. With this we can start the for loop at index 1.
🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-loops
Python For Loops - GeeksforGeeks
Python continue Statement returns the control to the beginning of the loop. ... # Prints all letters except 'e' and 's' for i in 'geeksforgeeks': if i == 'e' or i == 's': continue print(i)
Published   1 month ago
🌐
Codingem
codingem.com › home › python for loop with index: access the index in a for loop
Python For Loop with Index: Access the Index in a For Loop - codingem.com
March 14, 2024 - Here is a list of alternative ways ... index in Python. The most basic way to get the index of a for loop is by keeping track of an index variable. This is commonly taught in beginner-level programming courses.