0

I am attempting to add items to a new list from a primary list, then remove those moved items from the primary list. Essentially use and discard.

I have already attempted to use list comprehensions (Remove all the elements that occur in one list from another). Then I attempted to use a for loop as well as an if statement to check for the elements and remove them, though when I printed the original list once again, nothing changed.

Not sure what I am doing wrong but it is extremely frustrating:

your_hand_list = []
computer_hand_list = []
computer_hand_list.append (random.sample(card_list, 5))
your_hand_list.append (random.sample(card_list, 5))

print (your_hand_list, computer_hand_list)

for card in your_hand_list and computer_hand_list:
    if card in card_list:
        card_list.remove(card)
gnericblu
  • 1
  • 1

1 Answers1

0

Edit: Adding your code made it much easier to understand your issue. Specifically, the problem is this statement:

for card in your_hand_list and computer_hand_list:

The Python and operator does not work the way you were expecting it to in this context. Instead, the Python standard itertools library has a function called chain that will solve your problem. Here is a (greatly) simplified version of your code for illustration purposes.

Example:

from itertools import chain

card_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
your_hand_list = [1, 4, 7]
computer_hand_list = [3, 9, 10]

for card in chain(your_hand_list, computer_hand_list):
    if card in card_list:
        card_list.remove(card)

print(card_list)

Output:

[2, 5, 6, 8]
rhurwitz
  • 2,557
  • 2
  • 10
  • 18
  • I edited my post with a picture of the code, sorry for not doing that before, new to the whole python and stackoverflow thing. For clarification, I am making a Crazy Eighths type of game so I need to to remove the "card" that is given to the player from the original list of cards in order to prevent duplicates. – gnericblu Mar 29 '21 at 14:41
  • I wasn't given an error when executing the code, telling me it seemingly worked, but again, the original card_list was not changed at all? Not sure what I am doing wrong since I used your code practically. I am using Visual Studio Code for macOS, I even tried it in Pycharm in case it was the program. – gnericblu Mar 30 '21 at 13:50