TANMAYA TANMAYA - 1 month ago 5
Python Question

Python incorrect result

I have a small doubt.When running the following code in python I am not getting the desired result.Can anyone explain why?

x,temp=[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],[]

for y in x[:-1]:temp.append(max(y,x[x.index(y)+1]))

print temp


Output for the above code is:-

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 62]


But it should be-:

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 23]


The only error I am getting is at the last element 62 as it should be 23 .Can anyone explain the reason?

Answer

As asongtoruin mentions in the comment your code doesn't do what you want because the .index method finds the first matching element in the list. So when it's testing the final 4, it _doesn't test it against the 23, it tests it against the 62 following the first 4 in x.

Here's a better way.

x = [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]

temp = [max(u,v) for u,v in zip(x, x[1:])]
print(temp)

output

[62, 98, 98, 27, 23, 70, 98, 98, 93, 93, 53, 60, 60, 23]

FWIW, it's a good idea to avoid using .index unless you really need it because it has to scan linearly through the list looking for matches, so it's not very efficient.

Comments