Andersson
Andersson

Reputation: 52685

How to force Python to correctly identify list element index in FOR loop

There is a simple list, for example,

my_list = ['a', 'b', 'b', 'c', 'c']

I want to run through my_list[1:] with for loop to get previous element value for each iteration:

for i in my_list[1:]:
    print(my_list[my_list.index(i)-1])

I expected to see a b b c on output, but get a a b b instead. I guess this is because index() method search only for first i value, ignoring the fact that there are two elements "b" as well as two "c"...

How to fix this code to get expected output?

Upvotes: 0

Views: 116

Answers (5)

Synedraacus
Synedraacus

Reputation: 1045

You can always emulate the behaviour of C/Pascal/Perl/whatever 'for' instead of Python 'for' (which is actually more like foreach). Note that the range starts with 1 to avoid returning the last element on the first iteration.

for i in range(1, len(my_list)):
    print(my_list[i], my_list[i-1])

Not very Pythonic, but this approach is sometimes more intuitive for people with background in other languages.

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107347

The list.index() method will return the index of first occurrence of its argument. And since you have multiple duplicate items in your list it doesn't give you the expected result. You can use a simple slicing to get your expected output:

>>> my_list = ['a', 'b', 'b', 'c', 'c']
>>> 
>>> my_list[:-1]
['a', 'b', 'b', 'c']

Or if you want to access these items through a loop you can use zip() function like following:

>>> for i, j in zip(my_list,my_list[1:]):
...     print(i, j)
... 
a b
b b
b c
c c

Upvotes: 4

tobias_k
tobias_k

Reputation: 82929

As you noticed, using index does not work here, as it always finds the first position of the given element. Also, it is pretty wasteful, as in the worst case you have to search the entire list each time.

You could use enumerate with start parameter to get the element along with its index:

start = 1
for i, x in enumerate(my_list[start:], start):
    print(i, x, my_list[i-1]) # index, current, last

Upvotes: 1

Filip
Filip

Reputation: 128

This will do the trick:

for i in range(len(my_list)+1):
    try: print(my_list[i-1])
    except: print 'it is 1st iteration'

Upvotes: -1

Robᵩ
Robᵩ

Reputation: 168776

Matching elements with their predecessors or sucessors is a common use case for zip:

In [13]: for i,prior in zip(my_list[1:], my_list[0:]):
    print (prior)
   ....:     
a
b
b
c

Upvotes: 2

Related Questions