2

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?

5
  • For starters start iterating Pythonicly: instead of for index in range(len(array)):, use for element in array: Commented Apr 11, 2022 at 18:30
  • In the inner loop, do you mean arr2? Commented Apr 11, 2022 at 18:30
  • When you say "find a huge array's items in another huge array", what do you mean? that's not just iterating. Can you give an example with inputs and outputs? Commented Apr 11, 2022 at 18:37
  • Anyway, it sounds like you want to use sets/dicts for fast O(1) lookup Commented Apr 11, 2022 at 18:38
  • @Chris_Rands it means that i need to iterate trough two array with 200 items each. Which means im printing out 200*200 lines? Commented Apr 11, 2022 at 18:51

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

set(arr1).intersection(arr2) will work
Thank you, i went with your. solution :)
1

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.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.