Reputation: 25
I need to write loop for each value of the first list should to paired with each value of second list
list_1 = [1,2,3,4,5]
list_2 = [100,101,102]
for x in list_1:
for y in list_2:
pair_list =
expected output is [[1,100],[1,1001],[1,102],[2,100]....
Upvotes: 0
Views: 45
Reputation: 4472
You can try
list_1 = [1,2,3,4,5]
list_2 = [100,101,102]
print([[y, x] for y in list_1 for x in list_2])
Or
pair_list = []
for x in list_1:
for y in list_2:
pair_list.append([x,y])
print(pair_list)
Output
[[1, 100], [1, 101], [1, 102], [2, 100], [2, 101], [2, 102], [3, 100], [3, 101], [3, 102], [4, 100], [4, 101], [4, 102], [5, 100], [5, 101], [5, 102]]
This nested list comprehension will return a list of each combination between values in list_1 and list_2
Upvotes: 0
Reputation: 117856
You can use itertools.product
>>> from itertools import product
>>> list(product(list_1, list_2))
[(1, 100), (1, 101), (1, 102), (2, 100), (2, 101), (2, 102), (3, 100), (3, 101), (3, 102), (4, 100), (4, 101), (4, 102), (5, 100), (5, 101), (5, 102)]
Or if you want a list of lists, you can do something similar with a list comprehension
>>> [list(i) for i in product(list_1, list_2)]
[[1, 100], [1, 101], [1, 102], [2, 100], [2, 101], [2, 102], [3, 100], [3, 101], [3, 102], [4, 100], [4, 101], [4, 102], [5, 100], [5, 101], [5, 102]]
Upvotes: 1