0
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 ?

Nekoso
  • 113
  • 5
  • 1
    just create a new list `new = [x for x in list2 if x not in list1]` – georg Feb 25 '16 at 10:59
  • merge two list and use list(set(list_name)) to remove duplicates – Zealous System Feb 25 '16 at 11:02
  • 1
    Possible duplicate of [Remove all the elements that occur in one list from another](http://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another) – AlokThakur Feb 25 '16 at 11:08

4 Answers4

2

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.

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
2

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]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
0

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)
Forge
  • 6,538
  • 6
  • 44
  • 64
0
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
yael
  • 307
  • 1
  • 7