Common elements between two lists with no duplicates
- You are appending a list containing
i
toc
, soi not in c
will always returnTrue
. You should appendi
on its own:c.append(i)
Or
Simply use sets (if order is not important):
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = set(a) & set(b) # & calculates the intersection.
print(c)
# {1, 2, 3, 5, 8, 13}
EDIT As @Ev. Kounis suggested in the comment, you will gain some speed by usingc = set(a).intersection(b)
.
How to find the common elements of two lists?
Use sets
, its like a list, but can only hold unique items:
set(lista).intersection(listb)
Compare lists within a python to list to find common elements
One way is to run a counter over the flattened list and choose those that appeared more than once:
from collections import Counter
from itertools import chain
flattened = chain.from_iterable(many_lists)
result = [elem
for elem, count in Counter(flattened).items()
if count > 1]
to get
>>> result
[1, 11, 800, 7620]
Fastest way to find the common item between two lists in Python
This is very inefficient, and it only acquires the first common item in the two lists, not all of them, a better compact solution is by using sets.
Like this,
def common_item(l1, l2):
return list(set(l1).intersection(set(l2)))
OR
def common_item(l1, l2):
return list(set(l1) & set(l2))
which should return a list of all the elements that are common in the two lists, given that all the elements are unique.
If you have repeated elements in the lists, then you can try this approach which removes the element from the list if you encounter it, at the cost of runtime, which is insignificant when it is small.
def common_item(l1, l2):
res = []
for x in l1:
if x in l2:
res.append(x)
l2.remove(x)
return res
Compare two list of sets
You can enumerate over the zipped lists and filter the indices based on whether the pair of sets is disjoint:
list1 = [{'a','b'}, {'c','d'}, {'a','b','c'}, {'c','f'}]
list2 = [{'c','d','e'}, {'e','f'}, {'a','b','d'}, {'c','f'}]
indices = [i for i, (a, b) in enumerate(zip(list1, list2)) if a.isdisjoint(b)]
# [0, 1]
find common elements in two lists in linear time complexity
To find them in linear time you should use some kind of hashing. The easiest way in Python is to use a dict:
list1 = [1, 8, 5, 3, 4]
list2 = [5, 4, 1, 3, 8]
common = set(list1).intersection(list2)
dict2 = {e: i for i, e in enumerate(list2) if e in common}
result = [(i, dict2[e]) for i, e in enumerate(list1) if e in common]
The result
will be
[(0, 2), (1, 4), (2, 0), (3, 3), (4, 1)]
You can use something like this to format and print it:
for i1, i2 in result:
print(f"list1[{i1}] with list2[{i2}]")
you get:
list1[0] with list2[2]
list1[1] with list2[4]
list1[2] with list2[0]
list1[3] with list2[3]
list1[4] with list2[1]
Related Topics
Matplotlib: How to Create Axessubplot Objects, Then Add Them to a Figure Instance
Group by in Group by and Average
Removing Duplicates from a List of Lists
What Does the Slash Mean in Help() Output
Extracting Extension from Filename in Python
Determine Whether Integer Is Between Two Other Integers
Fast Punctuation Removal with Pandas
How to Return Dictionary Keys as a List in Python
How to Redirect 'Print' Output to a File
Plotting Time in Python with Matplotlib
How to Filter Foreignkey Choices in a Django Modelform
What's the Difference Between Globals(), Locals(), and Vars()
Python: Removing List Element While Iterating Over List
Checking Running Python Script Within the Python Script
How to Direct Output to a File When There Are Utf-8 Characters
How to Change the X Axis in Matplotlib So There Is No White Space