How to access previous/next element while for looping?

You can iterate through a list 3 at a time, or in n-tuples.

You can iterate through a list 3 at a time, or in n-tuples: aspn.activestate.com/ASPN/Cookbook/Pytho... aspn.activestate.com/ASPN/Cookbook/Pytho....

These will not create the desired effect of sliding window, which is what the original poster asked for – bgbg Nov 27 '08 at 15:06.

Expressed as a generator function: def neighborhood(iterable): iterator = iter(iterable) prev = None item = iterator.next() # throws StopIteration if empty. For next in iterator: yield (prev,item,next) prev = item item = next yield (prev,item,None) Usage: for prev,item,next in neighborhood(l): print prev, item, next Edit: I thought it would reduce the readability, but this way seem to look better.

I might do "prev, item = item, next" in this case. – Paul Fisher Nov 27 '08 at 17:31 To make this cycle infinitely (no StopIteration), do from itertools import cycle and change the second line to: iterator = cycle(iterable) – Dennis Williamson Dec 17 '09 at 1:50.

When dealing with generators where you need some context, I often use the below utility function to give a sliding window view on an iterator: import collections, itertools def window(it, winsize, step=1): """Sliding window iterator. """ it=iter(it) # Ensure we have an iterator l=collections. Deque(itertools.

Islice(it, winsize)) while 1: # Continue till StopIteration gets raised. Yield tuple(l) for I in range(step): l. Append(it.next()) l.popleft() It'll generate a view of the sequence N items at a time, shifting step places over.Eg.

>>> list(window(1,2,3,4,5,3)) (1, 2, 3), (2, 3, 4), (3, 4, 5) When using in lookahead/behind situations where you also need to deal with numbers without having a next or previous value, you may want pad the sequence with an appropriate value such as None. L= range(10) # Print adjacent numbers for cur, next in window(l + None ,2): if next is None: print "%d is the last number. " % cur else: print "%d is followed by %d" % (cur,next).

Check out the looper utility from the Tempita project. It gives you a wrapper object around the loop item that provides properties such as previous, next, first, last etc. Take a look at the source code for the looper class, it is quite simple. There are other such loop helpers out there, but I cannot remember any others right now.

Example: > easy_install Tempita > python >>> from tempita import looper >>> for loop, I in looper(1, 2, 3): ... print loop. Previous, loop. Item, loop.

Index, loop. Next, loop. First, loop.

Last, loop. Length, loop. Odd, loop.

Even ... None 1 0 2 True False 3 True 0 1 2 1 3 False False 3 False 1 2 3 2 None False True 3 True 0.

L=1,2,3 for i,item in enumerate(l): if item==2: get_previous=li-1 print get_previous >>>1.

Iterators only have the next() method so you cannot look forwards or backwards, you can only get the next item. Enumerate(iterable) can be useful if you are iterating a list or tuple.

I don't think there is a straightforward way, especially that an iterable can be a generator (no going back). There's a decent workaround, relying on explicitly passing the index into the loop body: for itemIndex, item in enumerate(l): if itemIndex>0: previousItem = litemIndex-1 else: previousItem = None The enumerate() function is a builtin.

Previous = None for item in someList: if item == target: break previous = item # previous is the item before the target If you want n previous items, you can do this with a kind of circular queue of size n. Queue = for item in someList: if item == target: break queue . Append( item ) if len(queue ) > n: queue .

Pop(0) if len(queue ).

Not very pythonic, but gets it done and is simple: l=1,2,3 for index in range(len(l)): if lindex==2: lindex-1 TO DO: protect the edges.

The most simple way is to search the list for the item: def get_previous(l, item): idx = l. Find(item) return None if idx == 0 else lidx-1 Of course, this only works if the list only contains unique items. The other solution is: for idx in range(len(l)): item = lidx if item == 2: lidx-1.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions