Question

[Solved] ValueError: item is not in list

I am making this simple code:

MyList=[]
valueA=1
valueB=2
valueC=3
MyList.append (valueA)
MyList.append (valueB)
MyList.append (valueC)
print (MyList)
print ([MyList].index(valueB))

I created it to try the [a].index(b) statement. As far as I know, and as far as I could find on the internet, this code should be fine.

I thought it would give the output: 0, because the index from valueB should be 0 (correct me if I’m wrong).

Instead it gave the output:

    print ([MyList].index(valueB))
ValueError: 2 is not in list

I dont think there are any problems with the difference between integer, string and float.

Can anybody tell me what I am doing wrong?

Solution #1:

[MyList] is a list consisting of a single item, which is MyList.

I don’t know why you have wrapped MyList in another list. You need to call index on MyList itself:

print(MyList.index(valueB))

And the result will be 1, not 0, because valueB is the second item in MyList.

Respondent: Daniel Roseman
Solution #2:

Your mistake was that you put my_list into another anonymous list at the last line.It should be like this:

MyList=[]
valueA=1
valueB=2
valueC=3
MyList.append (valueA)
MyList.append (valueB)
MyList.append (valueC)
print (MyList)
print (MyList.index(valueB))

Output:

[1, 2, 3]
1
Respondent: Inconnu
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy