+ 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?
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]
+ 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 .
+ 1
Arsalan thks for correcting me!