Created
December 26, 2018 22:54
-
-
Save bbookman/de9cae671eb144d7011768999470242b to your computer and use it in GitHub Desktop.
Python List Comprehension: Common number tuples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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) |
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
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.
# 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
This could simplify the comprehension:
[(i,i) for i in list_a if i in list_b]