Deleting elements from a list | Sololearn: Learn to code for FREE!


Deleting elements from a list

We got 2 lists, I'm trying to remove the common elements from the bigger list! This is my code: a =[ 2,3,4,5,1,2,3,2,3,4,5,6,7,8] b = [2,3,4,5,2,3] for i in range(len(b)): if b[i] in a: a.remove(b[i]) print(a) But it's not true! What's wrong with it?

9/19/2021 6:29:21 PM

Amirreza Hashemi

4 Answers

New Answer


Amirreza Hashemi , to do it with a loop you can use: a =[ 2,3,4,5,1,2,3,2,3,4,5,6,7,8] b = [2,3,4,5,2,3] # it is important not to iterate over the original list 'a', as indexes will change by deleting elements. use a copy of list 'a[:]' to iterate over. for num_a in a[:]: . if num_a in b: a.remove(num_a) print(a) # result is: [1, 6, 7, 8]


Check these links, "remove" method removes only first matching element. You can however do the following instead, a =[ 2,3,4,5,1,2,3,2,3,4,5,6,7,8] b = [2,3,4,5,2,3] print(list(set(a)-set(b))) Edit: Sorry Amirreza Hashemi i just didn't thought about duplicates as mentioned by Arsalan , check Lothar code for correct answer .


In the Abhay's solution, the duplicate items of the list 'a' are also removed. For example if there are two 7s in the a, there will be only one 7 in the output. In addition to the Lothar's solution, you can also use this: c = [x for x in a if x not in b]


Arsalan thks for correcting me!