Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from one list based on elements in another list

I have Two lists like this:

options = [['64', '32', '42', '16'], ['Sit', 'Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat', 'Puppy']]
right_answer = ['42', 'Sit', 'Puppy']

I want to remove the right_answer from options and get an output like this:

incorrect_answer = [['64', '32', '16'], ['Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat']]

I tried using .remove() but it clears the list:

for i in range(0,len(options)):
   incorrect_answers = options[i].remove(right_answer[i])
like image 952
Pushpesh Kumar Avatar asked Jul 01 '26 12:07

Pushpesh Kumar


1 Answers

A simple list comprehension with zip that doesn't mutate the original lists

incorrect_answers = [[answer for answer in possible if answer != correct] for possible, correct in zip(options, right_answer)]

Try it online!

like image 100
Samathingamajig Avatar answered Jul 03 '26 02:07

Samathingamajig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!