Let's say I have a list

g = [123, 321, 222, 111] for i in g: print i print 'a=%s, b=%s' % (i, '?') 

I need to overtake all the values ​​in the list and so that "a" takes the value "i", and "b" - the value "i-1", that is, the index number before it.

    3 answers 3

    Magic, the second attempt!

     g = [123, 321, 222, 111] previous = None for i in g: print 'a=%s, b=%s' % (i, previous) previous = i 
    • Come on ... Everything is so elementary ... it's time for me to rest) Thank you very much, otherwise I already broke my head))) - JackieChan

    If we are already talking about indexes, then this option:

     g = [123, 321, 222, 111] for i, a in enumerate(g): if i>0: print 'a=%s, b=%s' % (a, g[i-1]) 

    Conclusion:

     a=321, b=123 a=222, b=321 a=111, b=222 

    If you remove the condition, then for the first element the "previous" will be the last element:

     g = [123, 321, 222, 111] for i, a in enumerate(g): print 'a=%s, b=%s' % (a, g[i-1]) 

    Conclusion:

     a=123, b=111 a=321, b=123 a=222, b=321 a=111, b=222 
       def gen_pairs(lst): for i in xrange(len(lst) - 1): yield lst[i], lst[i + 1] for i, j in gen_pairs([123, 321, 222, 111]): print('%i %i' % (i, j))