Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the previous element when using a for loop? [duplicate]

Tags:

Possible Duplicates:
Python - Previous and next values inside a loop
python for loop, how to find next value(object)?

I've got a list that contains a lot of elements, I iterate over the list using a for loop. For example:

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 element before i. How can I achieve that?

like image 693
user469652 Avatar asked Oct 23 '10 05:10

user469652


People also ask

What is the Python code for repeat?

In repeat() we give the data and give the number, how many times the data will be repeated. If we will not specify the number, it will repeat infinite times. In repeat(), the memory space is not created for every variable.

How do you find the index of a value in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.


2 Answers

You can use zip:

for previous, current in zip(li, li[1:]):
    print(previous, current)

or, if you need to do something a little fancier, because creating a list or taking a slice of li would be inefficient, use the pairwise recipe from itertools

import itertools

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

for a, b in pairwise(li):
    print(a, b)
like image 90
SingleNegationElimination Avatar answered Oct 20 '22 06:10

SingleNegationElimination


Normally, you use enumerate() or range() to go through the elements. Here's an alternative using zip()

>>> li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]
>>> list(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 2nd element of each tuple is the previous element of the list.

like image 33
ghostdog74 Avatar answered Oct 20 '22 04:10

ghostdog74