2

Suppose I have a nested loop of the form:

for i in List1:
    for j in List2:
        DoSomething(i,j)

Can it be done as follows:

for i,j in combine(List1, List2):
    DoSomething(i,j)

Thanks in advance

So to clarify the combine function would do something as follows:

List1 = range(5)
List2 = range(5)
combine(List1, List2,)
>>> (0,0)
>>> (0,1)
>>> (0,2)
.
.
.
>>> (2,4)
>>> (3,0)
.
.
.

The itertools.product works perfectly

2
  • 1
    what is you actual problem you are trying to solve? Yes you can combine lists, but the nested loop works like a 2 dimensional array. How would like the combine function to behave? Please update your post to narrow your question. Commented Apr 19, 2017 at 14:51
  • I would say he wants to DoSomething in a nested-loop without explicitly nesting loops. IMO the question is not very verbose, but clear in this extent. And the perfect answer has already been given: stackoverflow.com/a/43498876/6525140 Commented Apr 19, 2017 at 22:42

1 Answer 1

5

You can use itertools.product

import itertools
for i,j in itertools.product(List1, List2):
    DoSomething(i,j)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.