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.

tupui
  • 5,738
  • 3
  • 31
  • 52
  • 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. – jez May 25 '17 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? – tupui May 25 '17 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)` – juanpa.arrivillaga May 25 '17 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. – juanpa.arrivillaga May 25 '17 at 17:56
  • Super thanks for your help – tupui May 25 '17 at 19:32

1 Answers1

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 :)

zwer
  • 24,943
  • 3
  • 48
  • 66
  • 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)? – tupui May 25 '17 at 17:47
  • 1
    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`. – zwer May 25 '17 at 17:52