Let the for loop be able to return the previously traversed item

Can we make the for loop be able to return the previously traversed item?

Return to where? Currently for loops are a statement and didn’t have a value. Can you provide example code of what you want to write and preferably also compare it to currently working alternatives?

like:
l = [1, 2, 3]
for i in l:
print(i)

That will print this, we kown:
1
2
3

could we make it to return the previously traversed item when the i is 2?
print:
1
2
1
2
3

Something like this?

lst = [1, 2, 3]
restart = True
while True:
    for i in lst:
        print(i)
        if i == 2 and restart:
            restart = False
            break
    else:
        break

or this?

lst = [1, 2, 3]
for n in range(2):
    for i in lst:
        print(i)
        if i == 2 and n == 0:
            break

A for loop is a very specific tool, and it doesn’t work the way you want it to, no.

The problem you’re trying to solve may have many solutions, depending on what the problem actually is, and why it’s a problem.


Starting over

For example, with your example the loop is actually completely starting over. If that’s all you need, there’s a clever way to do it in Python:

import random

# just to have a complete working example, let's say it's random whether we need to start over.
def something_bad_happened():
    return random.choice([True, False])

while True:
    for i in [1, 2, 3]:
        # Maybe you want to check after the print instead. It depends.
        if something_bad_happened():
            break # try the whole for loop over again
        print(i)
    else:
        break

Python loops can also have an else block which runs when the loop finishes “normally” (i.e. without breaking etc.):

When “something bad happens”, the for loop is broken, which means its else does not run, so the outer while loop continues.

When the loop succeeds, the break inside else breaks from the while loop, continuing the rest of the program.

However, there needs to be a reason why “something bad” will not “happen” the next time the for loop gets to the same point. Otherwise you are just stuck there :wink:


Using a specific “fancy” sequence

If you want to loop over a sequence like 1, 2, 1, 2, 3 explicitly, then the best way is to just construct that sequence ahead of time. There are tons of ways to do it, and you don’t even need to build a list. For example:

from itertools import chain, tee, islice

def first_two_then_everything(iterable):
    a, b = tee(iterable)
    return chain(islice(a, 2), b)

for i in first_two_then_everything([1,2,3]):
    print(i)

This itertools recipe will also work with special iterables like files or map or zip that can’t be indexed or “rewound”. (I tested it with a generator expression.) It uses tee to “remember” the first two values after retrieving them from the source, so that they can be repeated.

1 Like
l = ['a', 'b', 'c', 'd', 'e', 'f']
cut_off = 'd'

for n, i in enumerate(l):
    if i == cut_off:
        print(l[:n] + l[:n + 1])

I routinely use something like this:

 prev = None
 for item in whatever:
     if item == 3 and prev == 5:
         print(prev, item)
     prev = item

This is (a) trivial to do and (b) infrequent. I’d be against having a
for-loop gratuitously keep some reference to the previous item (if
that’s what you had in mind). It wastes memory and time.

And just knowing the previous item isn’t always what one wants. So this
seems very special purpose to me and easy to address when you actually
want it.

For that matter, if the goal is to think in terms of “the previous item” (or previous few items), that’s a whole other solved problem:

no, thats jast a example

to do this, we must have a new keyword in python, and we had to change how for loop works
like:
l = [1, 2, 3]
for i in l:
print(i)
if i == 2:
goback
print this:
1
2
1
2
3

I meen that return the previously traversed item, not starting over, last time.

I hope Cpython core exploitation can do this in python 3.13 or python 3.14
it can be useful.

Nobody here, as far as I can tell, can understand why you think so. That’s why you’re getting the answers you are.

I’m think of if we can creat a new keyword, it can return the previously traversed item in for or while loop

That does not address the problem. Let me ask directly:

Why would I, or anyone else who is not you, want to return the previously traversed item in the loop?

If we have this new keyword, what practical problem can we now easily solve that we couldn’t before?

like, you want user to input 3 numbers, but if users want to revise the input last time, we can use it, but now, we need another list and lots of code to do it

That sounds like an interactive problem, and nearly nothing to do with
for loops. I’d want to see a real programme where you needed to do this.

There are libraries like readline which make recalling the previous
line of input trivial for the user.

Nobody here seems to think this is worth modifying a core construct of
the language. Please show us a real world example where you wanted this.

1 Like

Your example will loop forever, not just print five numbers.

Ok, I’ll think about it

that’s what usually the Enter (or something fitting) is for in a Gui: the user can try all the keys but after Enter … :rofl: (unless AI finds a fly in the ointment)