Python list: how to read the previous item when used for a loop?

Possible duplicates:
Python - Previous and next values โ€‹โ€‹inside the
python for loop, how to find the next value (object)?

Hi all.

I have a list containing many elements, I iterate over the list using a for loop. for instance

li = [2,31,321,41,3423,4,234,24,32,42,3,24,,31,123]

for (i in li):
    print i

But I want to get the previous element i, how to do this?

I don't need to use a for loop, so feel free to change anything. Thank!

+3
source share
7 answers

Usually you use enumerateor range()to traverse items. Here is an alternative

>>> li = [2,31,321,41,3423,4,234,24,32,42,3,24,31,123]
>>> zip(li[1:],li)
[(31, 2), (321, 31), (41, 321), (3423, 41), (4, 3423), (234, 4), (24, 234), (32, 24), (42, 32), (3, 42), (24, 3), (31, 24), (123, 31)]

the second element of each tuple is the previous element of the list.

+17

zip:

for a, b in zip(li, li[1:]):
  print a, b

, - , li ( - ...),

import itertools

readahead = iter(li)
next(readahead)

for a, b in itertools.izip(li, readahead)
    print a, b
+12

li = range(10)

for i, item in enumerate(li):
    if i > 0:
        print item, li[i-1]

print "or..."   
for i in range(1,len(li)):
    print li[i], li[i-1]

:

1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
or...
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8

, .

last_item = None
for item in li:
    print last_item, item
    last_item = item
+6

, itertools :

from itertools import tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

for i, j in pairwise(li):
    print i, j
+2

. ( , .)

for i in range(1,len(li)):
  print li[i], li[i-1]
+1
j = None
for i in li:
    print j
    j = i
0
li = [2,31,321,41,3423,4,234,24,32,42,3,24,,31,123]

counter = 0
for l in li:
    print l
    print li[counter-1] #Will return last element in list during first iteration as martineau points out.
    counter+=1
-2

Source: https://habr.com/ru/post/1771035/


All Articles