Paulo
Paulo

Reputation: 519

Cannot get an index of a list item

I have these two lists:

list1= [1, 3, 8, 14, 20]

list2= [1, 2, 7, 8, 14, 20]

I obtained the common items between these two lists as follow: commonItems=list(set(list1).intersection(list2))

now randomly picked one of the common items as :

pick=random.sample(commonItems,1)

Now, when I try to identify the picked item index in one of the above lists as : PickedItemIndex=list1.index(pick)

I got this error: ValueError: [8] is not in list

even if, as you can see, item 8 really exists in list1

what is the problem? I am a new pythonic. Thank you in advance.

Upvotes: 0

Views: 209

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34086

The problem is that the type of variable pick is a list.

You need to pass an int to the index command:

In [314]: list1.index(pick[0])
Out[314]: 4

Upvotes: 2

Laurens Deprost
Laurens Deprost

Reputation: 1691

The error occurs because the variable 'pick' is a list. The code below will run without an error:

pick=random.sample(commonItems,1)
PickedItemIndex=list1.index(pick[0])

pick[0] is the first item of the list 'pick' (that contains only 1 element)

Upvotes: 2

Related Questions