Aamir Khan
Aamir Khan

Reputation: 324

Value error even though element is present inside the list in Python

I am trying to swap 2 elements of a list. Please look at this piece of code:

>>>a=[1,2,3,4]
>>>a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
ValueError: 2 is not in list

I am trying to swap 1 and 2 present at indices 0 and 1 respectively. Even though 2 is present in the list, I am getting a value error. Can anyone please explain why is it so?

Upvotes: 1

Views: 290

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

By the time the first assignment in the multiple assignment statement has been executed viz.:

 a[a.index(2)] = a[a.index(2)-1] 

2 will no longer exist in the list, so a.index(2) used in the next assignment target fails.

Bear in mind that the assignment to the targets is done starting from the left most so the first assignment replaces the value 2.

You can avoid the above scenario by simply storing the index of 2 before performing the assignment:

ind = a.index(2)
a[ind], a[ind-1] = a[ind-1], a[ind]

With this, you not only store the index but you avoid traversing the list 4 times with list.index.

Upvotes: 3

Related Questions