4

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?

Paul Rooney
21.7k9 gold badges47 silver badges64 bronze badges
asked Oct 27, 2016 at 11:27
2
  • 2
    When y is the final element in your list (4), x.index(4) = 0. It's the duplication of 4 in your list with the use of index that causes the problem. Commented Oct 27, 2016 at 11:54
  • That's the exact error and thankyou for pointing it out. Commented Oct 27, 2016 at 12:14

2 Answers 2

4

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.

answered Oct 27, 2016 at 12:03
Sign up to request clarification or add additional context in comments.

Comments

1

The end index of the slice is exclusive. Your value is -1 which means the last element which is exclusive - so it skips it.

Change x[:-1] to x[:] which will go through every element.

answered Oct 27, 2016 at 11:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.