Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:06
Show Gist options
  • Save bbookman/aca5b890a1f5ad64487594780301f82f to your computer and use it in GitHub Desktop.
Save bbookman/aca5b890a1f5ad64487594780301f82f to your computer and use it in GitHub Desktop.
Python List Comprehension: Find common numbers in two lists of numbers
'''
Find the common numbers in two lists (without using a tuple or set) list_a = [1, 2, 3, 4], list_b = [2, 3, 4, 5]
'''
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common = [a for a in list_a if a in list_b]
print(common)
@Alvaro8317
Copy link

But if you use repeated numbers on the list or lists of different length, is not going to work very well, I prefer to use the set, even if you say "without using a set".
print (set (a for a in list_a if a in list_b) )

@the-revival
Copy link

I guess he said 'without using a set' because using a set, this is easily achievable by using intersection. There's no need for a comprehension.

@Amine-Fadssi
Copy link

using nested loops

list_a = 1, 2, 3, 4
list_b = 2, 3, 4, 5
my_list = [element_b for element_b in list_b for element_a in list_a if element_b == element_a]
print(my_list)

@kandi1999
Copy link

kandi1999 commented Aug 8, 2024

using nested loops and function in the expression of list comprehension for it wouldn't add repeated numbers. Though it might be confusing

common_numbers = []
def f(x):
    common_numbers.append(x)
    return x

list_a = 1, 2, 3, 4, 
list_b = 2, 3, 4, 5,
my_list = [f(element_b) for element_b in list_b for element_a in list_a if element_b == element_a and element_b not in common_numbers]
print(my_list)

@Softwaredeveloper94rock
Copy link

list_a=1,2,3,4
list_b=2,3,4,5
list=[i for i in list_a for j in list_b if i==j]
Print(list)

@amit-75
Copy link

amit-75 commented Jan 3, 2025

list_a = [1,2,3,4]
list_b = [2,3,4,5]
common_numbers = [n for n in list_a if n in list_b]
print("Common numbers: ",common_numbers)

@Aishwarya-Wani18
Copy link

list_a = [1,2,3,4]
list_b = [2,3,4,5]
common_number = [num for num in list_b if num in list_a]
print(common_number)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment