Skip to content Skip to sidebar Skip to footer

Common Elements In Two Lists Python

I have two python lists generated from two different database tables list1= [''HZ1398043','HZ1395693','HZ1395532','HZ1395240','HZ1395194','HZ1395113','HZ1395036','HZ1395236','HZ139

Solution 1:

Look closely, your first list is actually a list with one item, a big string.

>>>list1= ["'HZ1398043','HZ1395693','HZ1395532','HZ1395240','HZ1395194','HZ1395113','HZ1395036','HZ1395236','HZ1396139','HZ1398028','HZ1395098','HZ1395998','HZ1395018','HZ1395829','HZ1398031','HZ1395708','HZ1398029','HZ1398030','HZ1398054''"]>>>len(list1)
1

Ideally, fix wherever you are getting the data to give you the right thing, if that's not possible, then you will need to parse the data.

You will want to do something like list1 = [item.strip("'") for item in list1[0].split(",")] to get the actual list (a simple list comprehension), then use one of your methods (the set method is the most efficient, although if you wish the keep duplicates and order, you will need to do the second method, although you can improve it by making a set of list2 beforehand to check for membership in).

Solution 2:

This is what they should be:

list1= ['HZ1398043','HZ1395693','HZ1395532','HZ1395240','HZ1395194','HZ1395113','HZ1395036','HZ1395236','HZ1396139','HZ1398028','HZ1395098','HZ1395998','HZ1395018','HZ1395829','HZ1398031','HZ1395708','HZ1398029','HZ1398030','HZ1398054']
list2= ['', '', '', '', '', 'HZ1395018', 'HZ1395036', 'HZ1395098', 'HZ1395113', 'HZ1395194', 'HZ1395236', 'HZ1395240', 'HZ1395532', 'HZ1395693', 'HZ1395708', 'HZ1395829', 'HZ1395998', 'HZ1396139', 'HZ1398028', 'HZ1398029', 'HZ1398031', 'HZ1398043', 'HZ1397932', 'HZ1397949', 'HZ1398004', 'HZ1398021', 'HZ1398030', 'HZ1397940', 'HZ1397941', 'HZ1398010','', '', '']

Your code works after you fix them.

Solution 3:

def compare(list1,list2):
ln= []
for i in list1:
    if i  in list2:
       ln.append(i)
returnln

print(compare(list1,list2))

not optimise but easy to understand.

Solution 4:

First you need to make a proper list out of list1, this can be done with something like:

list1 = [item.strip("'") for item in list1[0].split(",")]

Then your code should work just fine. An alternative (more compact but slower) way to find common elements would be:

common = filter(lambda x:x in list1,list2)

Post a Comment for "Common Elements In Two Lists Python"