Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbookman/de9cae671eb144d7011768999470242b to your computer and use it in GitHub Desktop.
Save bbookman/de9cae671eb144d7011768999470242b to your computer and use it in GitHub Desktop.
Python List Comprehension: Common number tuples
'''
Produce a list of tuples consisting of only the matching numbers in these lists list_a = [1, 2, 3,4,5,6,7,8,9], list_b = [2, 7, 1, 12]. Result would look like (4,4), (12,12)
'''
list_a = [1, 2, 3,4,5,6,7,8,9]
list_b = [2, 7, 1, 12]
result = [(a, b) for a in list_a for b in list_b if a == b]
print(result)
@gonzalezloaizar
Copy link

gonzalezloaizar commented Apr 4, 2022

This could simplify the comprehension:

[(i,i) for i in list_a if i in list_b]

@Linuszand
Copy link

for a in list_a:
for b in list_b:
first_tuple, second_tuple = a, b
if first_tuple == second_tuple:
print([(first_tuple, second_tuple)])

idk if this is correct but this is the normal way

@adish-ct
Copy link

adish-ct commented Jan 13, 2023

way 1:

list_1 = [1,2,3,4,5,6,7]
list_2 = [3,5,6,9,0,8]
result = [(num1,num1) for num1 in list_1 if num1 in list_2]
print (result)

way 2 :

for num in list_1:
if num in list_2:
print ((num , num))

list_1 and list_2 consider common for both code.

@Amine-Fadssi
Copy link

# Produce a list of tuples consisting of only the matching numbers in lists
list_a = 1, 2, 3, 4, 5, 6, 7, 8, 9
list_b = 2, 7, 1, 12
my_list = [(num, num) for num in list_a if num in list_b]
print(my_list)

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