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)
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.
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.
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.
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
l = [1, 2, 3]
for i, j in zip(l, l[1:]):
print(i, j)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With