Skip to content Skip to sidebar Skip to footer

In Python, Whats The Difference Between A List Comprehension With A List And A Tuple?

Playing around with iPython, I was surprised to discover that given a list f of objects each supporting some method x() (that, say, prints out 'Hi!'), the expression: (y.x() for y

Solution 1:

Some people treat tuples as read-only lists, and that works in some contexts. But that is not the semantic intention of tuples. Lists are intended to be used for variable length structures of homogeneous elements (elements with a shared type). Tuples are intended for fixed length structures in which each indexed position contains a certain type of element.

enumerate(lst) is an example of this. It returns a variable-length list of tuples. Each tuple has exactly two elements, the first of which is always an integer, and the second of which is from lst.

With that understanding, a tuple generator is a bit nonsensical. That is probably why.

Edit:

As for directly generating a tuple, you can do a little bit better than your example. This also works:

tuple(y.x() for y in f)

That passes a generator to the tuple() method, which constructs a tuple, but doesn't create an intermediate list.

To be clear, there is no tuple involved in (y.x() for y in f), but there is a tuple in t = 1, 2, 3. It's not the parens that make the tuple. It's the commas.

Solution 2:

Question: Why is the first expression not generating a tuple of the values obtained from the generator the way the list is being built?

That is not what is designed to do. See PEP-289Tutorial is always a good place to start looking for answers. Generator ExpressionsExpression lists - describes the use of a comma for defining a tuple

So is it true that it is not possible to directly get a tuple as the result of generating a list comprehension?

No -not like a list comprehension, it is a generator. It is designed to yield individual elements for each iteration.

Post a Comment for "In Python, Whats The Difference Between A List Comprehension With A List And A Tuple?"