0

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Paulo
  • 319
  • 1
  • 3
  • 12

2 Answers2

2

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)

Laurens Deprost
  • 1,653
  • 5
  • 16
2

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
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
  • 3
    Note: An alternative approach is to use the knowledge that [there is exactly one element picked to unpack it at time of selection](https://stackoverflow.com/a/33161467/364696), so it's the expected scalar value, e.g. `[pick] = random.sample(commonItems, 1)` will unpack the resulting `list` immediately, so you can use `pick` directly without indexing thereafter. – ShadowRanger Dec 26 '18 at 14:01