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 PMAmirreza Hashemi
4 AnswersNew 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, https://www.google.com/url?sa=t&source=web&rct=j&url=https://docs.python.org/3/tutorial/datastructures.html&ved=2ahUKEwjZpaSC14vzAhU4rZUCHUNcB1AQFnoECDUQAQ&sqi=2&usg=AOvVaw16HjD78khY_g9UUcJL3zlb https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.guru99.com/python-list-remove-clear-pop-del.html&ved=2ahUKEwjZpaSC14vzAhU4rZUCHUNcB1AQFnoECBQQAQ&sqi=2&usg=AOvVaw2WywaQUyY8fDFZYllpyVA2 "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!