Reputation: 347
Is there a better way for looping over every combination of multiple lists in Python? For example...
list1 = [1,2,3,4]
list2 = [6,7,8]
for i in list1:
for j in list2:
print(str(i) + ", " + str(j))
1, 6
1, 7
1, 8
2, 6
2, 7
2, 8
3, 6
3, 7
3, 8
4, 6
4, 7
4, 8
I ask because I would like to break out of both loops once a value is found. I do not want to use a bool flag to break out of the top level loop. All answers I have seen so far say to use zip, but that is not the same thing. zip would produce the following.
1, 6
2, 7
3, 8
If you use map, you get the following, which is also not what I am looking for.
1, 6
2, 7
3, 8
4, None
Upvotes: 1
Views: 3228
Reputation: 8222
If you need to know where you were in the scan when the break condition arose, you can use list comprehensions and enumerate
together
for i,a,j,b in [ x+y for x in enumerate([11,12,13,14]) for y in enumerate([16,17,18]) ]:
print( i,a,j,b)
if a==13 and b==17: break
print(i,j) # get 2 1
Upvotes: 1
Reputation: 3485
If you don't want to use itertools.product
as suggested in another answer, you can wrap it in a function and return:
list1 = [1,2,3,4]
list2 = [6,7,8]
def findNumbers(x, y):
for i in list1:
for j in list2:
print(str(i) + ", " + str(j))
if (x, y) == (i, j):
return (x, y)
Output:
>>> findNumbers(2, 7)
1, 6
1, 7
1, 8
2, 6
2, 7
(2, 7)
Upvotes: 1
Reputation: 21663
You might like to see product
used in a simple code.
product
is an iterator that returns elements of the cross-product of list1
and list2
one at a time.for
-loop we watch for the appearance of a certain pair, and break
out of the loop if and when we encounter it.--
>>> list1 = [1,2,3,4]
>>> list2 = [6,7,8]
>>> from itertools import product
>>> for i, j in product(list1, list2):
... if (i,j)==(2,7):
... print (i,j)
... break
...
2 7
Upvotes: 0
Reputation: 1769
Have you tried using a list comprehension
[(x, y) for x in [1,2,3,4]
for y in [6,7,8]]
Upvotes: 2
Reputation: 2682
You can use itertools.product
like so:
list1 = [1,2,3,4]
list2 = [6,7,8]
find_this_value = (1, 8)
found_value = False
for permutation in itertools.product(list1, list2):
if permutation == find_this_value:
found_value = True
break
if found_value:
pass # Take action
itertools.product
returns a generator with all of the possible permutations of the 2 lists. Then, you simply iterate over those, and search until you find the value you want.
Upvotes: 2
Reputation: 10669
You can use the product
function.
You can read more in here
Roughly equivalent to nested for-loops in a generator expression
import itertools
print (list(itertools.product(list1, list2)))
# [(1, 6), (1, 7), (1, 8), (2, 6), (2, 7), (2, 8), (3, 6), (3, 7), (3, 8), (4, 6), (4, 7), (4, 8)]
Upvotes: 0