shahab-qazavi
shahab-qazavi

Reputation: 362

best way of search items of list in another list python?

I have a list with 32683 of length and i have to search items of this list in another list with 2905 of length that i wrote it like this:

for item in phone_register_users:
    if item not in service_users_ids:
       counter += 1

(length of phone_register_users is 32683 and service_users_ids is 2905) but it takes about 14 seconds to complete it and this is too much, how can i improve this?

Upvotes: 2

Views: 108

Answers (2)

Khakhar Shyam
Khakhar Shyam

Reputation: 499

You can use set:

set1 = set(phone_user_register_list1)
set2 = set(services_user_ids_list2)
unq = set1.intersection(set2)

from the intersection you can get the list of elements which in phone user register and service users id both.

So to do the counter of element which are in phone register but not in services user id use:

counter = len(phone_register_user)-len(unq)

Upvotes: 2

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

According to the wiki, the complexity for list to search is O(n), you can try using a set or dict to reduct it to O(1), something like this should be enough:

service_users_ids = [...]
phone_register_users = [...]
service_users_ids_set = set(service_users_ids)
for item in phone_register_users:
    if item not in service_users_ids_set:
        counter += 1

Upvotes: 1

Related Questions