Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the previous/next element in a for loop?

Is there a way to access a list's (or tuple's, or other iterable's) next or previous element while looping through it with a for loop?

l = [1, 2, 3]
for item in l:
    if item == 2:
        get_previous(l, item)
like image 364
Bartosz Radaczyński Avatar asked Nov 27 '08 13:11

Bartosz Radaczyński


People also ask

How do you go back to the beginning of a while loop?

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

How do you go to the next line in a for loop in Python?

Here's a simple way to do it for a file object: with open('foo. txt', 'r') as rofile: for line in rofile: print line, if line. strip() == 'foo': for _ in xrange(3): # get the next 3 lines try: line = rofile.

How do you get the next value in Python?

Python next() FunctionThe next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.


3 Answers

Expressed as a generator function:

def neighborhood(iterable):
    iterator = iter(iterable)
    prev_item = None
    current_item = next(iterator)  # throws StopIteration if empty.
    for next_item in iterator:
        yield (prev_item, current_item, next_item)
        prev_item = current_item
        current_item = next_item
    yield (prev_item, current_item, None)

Usage:

for prev,item,next in neighborhood(l):
    print prev, item, next
like image 64
Markus Jarderot Avatar answered Oct 21 '22 17:10

Markus Jarderot


l = [1, 2, 3]

for i, j in zip(l, l[1:]):
    print(i, j)
like image 32
Vicky Liau Avatar answered Oct 21 '22 16:10

Vicky Liau


l = [1, 2, 3]
for i, item in enumerate(l):
    if item == 2:
        previous = l[i - 1]
        print(previous)

Output:

1

This will wrap around and return the last item in the list if the item you're looking for is the first item in list. In other words changing the third line to if item == 1: in the above code will cause it to print 3.

like image 12
Rudiger Wolf Avatar answered Oct 21 '22 16:10

Rudiger Wolf