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

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 â€¦ (unless AI finds a fly in the ointment)