Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:54
Show Gist options
  • 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)
@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