[New-bugs-announce] [issue35245] list comprehension for flattened or nested list differ too much

Yechoh report at bugs.python.org
Wed Nov 14 08:24:33 EST 2018


New submission from Yechoh <martin.huyben at home.nl>:

Suppose we have:
forest = [[1,2],[3,4]]
and we want:
l1 = [['1','2'],['3','4']]
we could write:
l1 = [[str(leaf) for leaf in tree] for tree in forest]

Now if we want:
l2 = ['1','2','3','4']
What I expect to need to write is:
l2 = [str(leaf) for leaf in tree for tree in forest]
However, this gives an error:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'tree' is not defined
Instead, I should write:
l2 = [str(leaf) for tree in forest for leaf in tree]
Notice the different order.
I would prefer if the first version of constructing l2 over the second, since it follows closer to the reading order.
Also, it is closer to the comprehension for a nested list, so changing a nested list comprehension to a flattened list comprehension is easy.

----------
messages: 329906
nosy: Yechoh
priority: normal
severity: normal
status: open
title: list comprehension for flattened or nested list differ too much
type: enhancement

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35245>
_______________________________________


More information about the New-bugs-announce mailing list