Skip to content
Advertisement

Finding intersections between two lists

Edit: I was using Jupyter notebook, I had two different scripts in a row while working, The script shown here is one, and the error shown here is from the other script. (mistake) Thanks for your time! I intentionally learned more though.

I’m trying to find an intersection between 10000 randomly generated lists of 6 elements numbers between 1 to 49 and a single list that I wrote myself also 1 to 49…

I tried using def like in the following script:

import random
lst1 = [7, 10, 21, 35, 48, 19]
lst2 = []
for i in range(10000):
    r = random.sample(range(1, 50), 6)
    lst2.append(r)
 #HERE #(   
def intersection(lst1, lst2): 
    lst3 = [value for value in lst1 if value in lst2] 
    return lst3 #)
    
    
#print(results)   
print("------------")
print(Intersection(lst1, lst2))

but I get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-88-0caf870aa4e6> in <module>()
     13 #print(results)
     14 print("------------")
---> 15 print(Intersection(lst1, lst2))

<ipython-input-51-a4e2d32a8078> in Intersection(lst1, lst2)
      7 
      8 def Intersection(lst1, lst2):
----> 9     return set(lst1).intersection(lst2)
     10 
     11 

TypeError: unhashable type: 'list'

Is there something I’m missing? I tried to look online but couldn’t find any solutions!

Advertisement

Answer

I changed list2 just to show that code is working you have some error in your code you can do something like that:

import random

lst1 = [7, 10, 21, 35, 48, 19]
lst2 = [6,7,10]
# for i in range(10000):
#     r = random.sample(range(1, 50), 6)
#     lst2.append(r)


# HERE #(
def intersection(lst1, lst2):
   lst3 = [value for value in lst1 if value in lst2]
   return lst3  # )

def Intersection(lst1, lst2):
   return set(intersection(lst2,lst1))
print(Intersection(lst1, lst2))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement