<generator object <genexpr> at ... > and <list_reverseiterator object at ... >

Luigi Pizza (6120 points)
11 20 65
asked Oct 14, 2021 in Programming in Python by Luigi Pizza (6,120 points)
recategorized Nov 1, 2021 by andrea.sterbini
As i was trying to find something interesting to write as a comment, i came across this generation of an object(?). This happened also in Professor Spognardi's lecture, but he said that we will be studying these in the future. What I wanted to ask are some tricks for not showing this, and maybe a simple explanation. Thank you!

P.S. i came across this when converting a list of lists into a tuple of tuples and when I wanted to create, given a tuple, its reverse of reversed elements:

tuple_of_tuples = (tuple(element) for element in list_of_lists)
print("The converted tuple of tuples : ", tuple_of_tuples)

# <generator object <genexpr> at ... >


t2=reversed([tuple(reversed(list(element))) for element in t1])

# <list_reverseiterator object at ... >

P.P.S. I know how to resolve these problems, just divide both of them into more lines of code, I just wanted to know why writing it like this is not possible

2 Answers

Best answer
ruben.ciranni (4650 points)
7 13 31
answered Oct 14, 2021 by ruben.ciranni (4,650 points)
selected Oct 18, 2021 by Luigi Pizza
Considering the first example (the problem is the same in both), when you use that notation what you are actually assigning to tuple_of_tuples is not a tuple, but a generator object created from the generating expression included in the parenthesis (). (If you want to explore generator objects I suggest you this article: https://realpython.com/introduction-to-python-generators/).

In order to do what is your aim you can just first assign to tuple_of_tuples a list of tuples (you can do that maintaining your notation but using brackets [] instead of parenthesis ()), and then converting the obtained list in a tuple.
1899325 (5730 points)
0 0 15
commented Oct 14, 2021 by 1899325 (5,730 points)
I've read the article you've suggested and I've also found this interesting one to share https://www.geeksforgeeks.org/generators-in-python/
andrea.sterbini (172680 points)
511 927 1776
answered Oct 14, 2021 by andrea.sterbini (172,680 points)
In python a "list comprehension" with parentheses () produces a generator and not a tuple.

If you want a tuple just give the generator to the tuple constructor

   tuple(tuple(element) for element in list_of_lists)
Luigi Pizza (6120 points)
11 20 65
commented Oct 15, 2021 by Luigi Pizza (6,120 points)
Thank you professor for the explanation. How about the second example, the one with reversed?