1

I want to perform:

for i in list_a:
    for j in list_b[i]:
        print(i, j)

Is it possible to do it using itertools? I am looking for something like:

for i, j in itertools.product(list_a, list_b[i])

I want to do that for speed and readability.

5
  • 1
    I don't think it's possible to flatten this in any way that improves speed or readability. The nested approach seems to me to be the natural and most efficient way to do this. You could write it all on one physical line by writing it as a list comprehension or generator expression, e.g: [ call_some_function(i,j) for i in list_a for j in list_b[i] ], but that's still fundamentally a nested for-loop. Commented May 25, 2017 at 17:34
  • OK but what would be the fastest, write a list comprehension and iterate over it with a function or create a function that yield something and iterate over it? Commented May 25, 2017 at 17:49
  • If you want a list, use a list comprehension. If you want a generator, use a generator expression: stuff = (call_some_function(i, j) for i in list_a for j in list_b[i]) And then you can iterate over that lazily without wasting memory materializing a list: for thing in stuff: do_some_more_stuff(thing) Commented May 25, 2017 at 17:55
  • A pure for-loop approach would probably be faster than using a generator expression, though. But a list comprehension could be slightly faster than an equivalent for-loop. Commented May 25, 2017 at 17:56
  • Super thanks for your help Commented May 25, 2017 at 19:32

1 Answer 1

1

itertools won't give you speed in most cases (but will give you stability and save you time so use it whenever possible) as for both readability and speed - nothing beats list comprehension :

your_list = [(i, j) for i in list_a for j in list_b[i]]

Then you can print it if you wish :)

Sign up to request clarification or add additional context in comments.

2 Comments

OK thanks so if I want to do something more complicated than a print, I suppose that I have to create a function and pass it the list (or generator)?
Yep, you can call your function within the generator instead of creating the tuple, if you need to collect the responses from that function. Otherwise there is no point in the generator apart from being in one line and producing a non-needed list.

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.