1

I want a way to remove an element from the list after selecting it with the random so as not to be selected again. When i am trying to run this code:

import random
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1) - 1)
x=(list2[choice1])
list1.remove(choice1)
list2.remove(x)
print(x)
print(list1[choice1])
print(list2[choice1])

Then I get this error: ValueError: list.remove(x): x not in list

newhere
  • 19
  • 3
  • 1
    If you had posted the full traceback, you would have seen that the error happens on the line `list1.remove(choice1)`. And indeed, this number is not in `list1`. Unfortunately, you named your variable `x` - the same one used by the error message. – Mr. T Jan 25 '18 at 16:53
  • i know that, but i want to know how to solve this error. – newhere Jan 25 '18 at 16:56
  • Well, then you should have described, what you were trying to achieve with `list1.remove[choice]`. I assume this here: https://stackoverflow.com/q/627435/8881141 – Mr. T Jan 25 '18 at 16:58
  • sorry, i edited it – newhere Jan 25 '18 at 17:02
  • guys stop posting me other threads!!! I have read them before i asked. – newhere Jan 25 '18 at 17:05

1 Answers1

0
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1) - 1)

The elements in your list2 isn't in list1. You generate random number and get the element from list2, and try to remove from list1. The error is correct, the item in list2 is not in list1

What you can do is print out x and remove it only if it exists in list1

if x in list1:
    list1.remove(x)

Be aware, list.remove(param) the param here is the item at specific index other than the index value

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
  • dude the error is coming when i am trying to remove something from the list 1. – newhere Jan 25 '18 at 17:08
  • @newhere I know you can remove item `x` from list2 but `choice1` is index other than item, python list remove() take item as parameter other than index of the item – Haifeng Zhang Jan 25 '18 at 17:09
  • yes, but its different item. the items in both lists are in purpose different. the purpose is to pick a random item from the first list and pick the item from the second list which is in the same position as this of the first one. then i want those two items to be removed from the lists so as not to be selected again. – newhere Jan 25 '18 at 17:14