adeen-s
adeen-s

Reputation: 156

index(max(my_list)) in list comprehension gives all instances of the max value instead of just the first occurrence

Consider the following code snippet -->

li = [3,1,2,3]
print([x+99 if li.index(x)!=li.index(max(li)) else x-(99*(len(li)-1)) for x in li ])

I was expecting the output to be :

[-294, 100, 101, 102]

but the actual output on running the program was :

[-294, 100, 101, -294]

Why do i get both instances of the maximum value in the list instead of just the first occurrence?

How exactly are list comprehensions evaluated and how is that responsible for the output in my program ?

Upvotes: 1

Views: 247

Answers (1)

Ajax1234
Ajax1234

Reputation: 71461

You have multiple 3s in your list. The implementation of index is such that it finds only the index of the first occurrence of the value passed to it. Instead, use enumerate:

li = [3,1,2,3]
l1 = [x+99 if i!=li.index(max(li)) else x-(99*(len(li)-1)) for i, x in enumerate(li)]

Output:

[-294, 100, 101, 102]

Upvotes: 2

Related Questions