nerdenator
nerdenator

Reputation: 1297

Python: Print a generator expression's values when those values are itertools.product objects

I'm trying to dig into some code I found online here to better understand Python.

This is the code fragment I'm trying to get a feel for:

from itertools import chain, product

def generate_groupings(word_length, glyph_sizes=(1,2)):
    cartesian_products = (
        product(glyph_sizes, repeat=r)
        for r in range(1, word_length + 1)
    )

Here, word_length is 3.

I'm trying to evaluate the contents of the cartesian_products generator. From what I can gather after reading the answer at this SO question, generators do not iterate (and thus, do not yield a value) until they are called as part of a collection, so I've placed the generator in a list:

list(cartesian_products)
Out[6]: 
[<itertools.product at 0x1025d1dc0>,
 <itertools.product at 0x1025d1e10>,
 <itertools.product at 0x1025d1f50>]

Obviously, I now see inside the generator, but I was hoping to get more specific information than the raw details of the itertools.product objects. Is there a way to accomplish this?

Upvotes: 0

Views: 133

Answers (1)

DSLima90
DSLima90

Reputation: 2838

if you don't care about exhausting the generator, you can use:

list(map(list,cartesian_products))

You will get the following for word_length = 3

Out[1]:
[[(1,), (2,)],
 [(1, 1), (1, 2), (2, 1), (2, 2)],
 [(1, 1, 1),
  (1, 1, 2),
  (1, 2, 1),
  (1, 2, 2),
  (2, 1, 1),
  (2, 1, 2),
  (2, 2, 1),
  (2, 2, 2)]]

Upvotes: 1

Related Questions