Deleting elements from a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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?

19th Sep 2021, 6:29 PM
Amirreza
Amirreza - avatar
4 Answers
+ 6
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]
19th Sep 2021, 7:18 PM
Lothar
Lothar - avatar
+ 7
Check these links, https://www.google.com/url?sa=t&source=web&rct=j&url=https://docs.JUMP_LINK__&&__python__&&__JUMP_LINK.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 .
19th Sep 2021, 6:38 PM
Abhay
Abhay - avatar
+ 3
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]
19th Sep 2021, 7:41 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 1
Arsalan thks for correcting me!
19th Sep 2021, 7:48 PM
Abhay
Abhay - avatar