J
J
Jay Marlow2016-06-01 15:39:30
Python
Jay Marlow, 2016-06-01 15:39:30

How to print the difference between two lists more quickly?

There are two lists

list1 = ['1111', '2222', '3333', '4444']
list2 = ['1111', '4444']

These two lists should actually be more than 10,000 values.
It is necessary to find the difference from these two lists and add them to the third one.
Currently, the following far from ideal approach is used:
list3 = []

for i in list1:
    if i not in list2:
        list3.append(i)

With small amounts of values ​​in the lists, this approach works quite tolerantly based on time.
But when the values ​​approach a large number, this enumeration will take some time.
How to speed up the process of finding the difference in lists?
Advised to use operator.sub:
>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> list(map(operator.sub, A, B))
[2, 1, 0, 4]

... but as I understand it, it does not exactly what it needs. Namely, it simply subtracts the values, which is completely inappropriate in my case. Or maybe there's a way to use it in my key that I haven't figured out yet.
I would be grateful for any advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2016-06-01
@kolumbou

list1 = ['1111', '2222', '3333', '4444']
list2 = ['1111', '4444']
set(list1) - set(list2)
{'3333', '2222'} #вывод

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question