crazybrain
crazybrain

Reputation: 3

Chaining multiple for loops together into one

I have two lists read from a file that look something along the lines of this:

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 0]

I then have a for loop that needs to call both of those lists:

res = []
for i in list1:
    for x in list2:
        if i + x * 2 == 10:
             res.append((i,x))

What I want to do is chain the for loops into one, so that it will only go through each number once, for example:

res = []
for i in list1 and x in list2:
    if i + x * 2 == 10:
        res.append((i,x))

Doing the above now, will output an error that x is not defined:

>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8, 9, 0]
>>> res = []
>>> for i in list1 and x in list2:
...     if i + x * 2 == 10:
...         res.append((i,x))
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> 

How can I go about doing this pythonically?

Upvotes: 0

Views: 113

Answers (2)

endless
endless

Reputation: 114

Try zip itertools.product :

import itertools
...
for i, x in itertools.product(list1, list2):
   if i + x * 2 == 10:
       res.append((i, x))

Upvotes: 4

Levi Lesches
Levi Lesches

Reputation: 1611

What I do is use a range loop, i.e. looping over possible indices instead of elements. Of course, you'd have to make sure that the lists are the same length, but it is really helpful. Implemented in your situation:

res = []
for index in range (len (list1)):
    if list1 [index] + list2 [index] * 2 == 10: res.append ((list1 [index], list2 [index]))

And if I dare, a one-liner:

res = [(list1 [index], list2 [index]) for index in range (len (list1)) if list1 [index] + list2 [index] * 2 == 10]

Remember, this only cross-searches lists, and doesn't loop over list2 for every element in list1.

Upvotes: 0

Related Questions