Reputation: 113
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [10,11,12,13,5,7]
and now i want that list2 should be cutted for same elements in list1 and list2
--> list2 = [10, 11, 12, 13]
5 and 7 is deleted because they are also in list1.
this is what i tried:
for i in range(len(list1)):
test = list1[i]
if test in list2:
del list2[list1[i]]
print(list2)
but list2 is the same as before :-(
hope you can help me EDIT: Sorry i forgot to say that the lists have got dates in datetime type. does it still work ?
Upvotes: 0
Views: 111
Reputation: 21476
You can do some easy ways:
>>> list1 = [1,2,3,4,5,6,7,8,9]
>>> list2 = [10,11,12,13,5,7]
>>> [item for item in list2 if item not in list1]
[10, 11, 12, 13]
Or, you can use filter
,
>>> filter(lambda item: item not in list1, list2)
[10, 11, 12, 13]
Or you can use generator function
like this,
>>> def diff_list(lst1, lst2):
... for item in lst1:
... if item not in lst2:
... yield item
...
>>> list(diff_list(list2, list1))
[10, 11, 12, 13]
Upvotes: 2
Reputation: 4538
Try this, first cast both list
to set
, now easily you can find differnce between two set
then cast result to list
and assign that to list2
:
list2 = list(set(list2)-set(list1))
list2 # [10, 11, 12, 13]
However this works only when you dont have duplicates in lists.
Upvotes: 2
Reputation: 337
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [10,11,12,13,5,7]
list2 = [i for i in list2 if not i in list1]
print list2
Upvotes: 0
Reputation: 6844
Your deletion is wrong, you are deleting the element in list2
on index list1[i]
instead of deleting list2[index_in_list2]
or using remove
like this list2.remove(list1[i])
for item in list1:
if item in list2:
list2.remove(item)
Upvotes: 0