Sipos Péter
Sipos Péter

Reputation: 138

Quick way to iterate through two arrays python

I've had multiple scenarios, where i had to find a huge array's items in another huge array. I usually solved it like this:

for i in range(0,len(arr1)):
        for k in range(0,len(arr1)):
            print(arr1[i],arr2[k])

Which works fine, but its kinda slow. Can someone help me, how to make the iteration faster?

Upvotes: 2

Views: 1639

Answers (3)

SergFSM
SergFSM

Reputation: 1491

if your array has duplicates and you want to keep them all:

arr1 = [1,2,3,4,5,7,5,4]
arr2 = [4,5,6,7]

res = [i for i in arr1 if i in arr2]
>>> res
'''
[4, 5, 7, 5, 4]

or using numpy:

import numpy as np

res = np.array(arr1)[np.isin(arr1, arr2)].tolist()
>>> res
'''
[4, 5, 7, 5, 4]

Upvotes: 1

NONONONONO
NONONONONO

Reputation: 682

arr1 = [1,2,3,4,5]
arr2 = [4,5,6,7]
same_items = set(arr1).intersection(arr2)
print(same_items)
Out[5]: {4,5}

Sets hashes items so instead of O(n) look up time for any element it has O(1). Items inside need to be hashable for this to work. And if they are not, I highly suggest you find a way to make them hashable.

Upvotes: 3

lemon
lemon

Reputation: 15482

If you need to handle huge arrays, you may want to use Python's numpy library, which assists you with high-efficiency manipulation methods and avoids you to use loops at all in most cases.

Upvotes: 1

Related Questions