2 ms·
What's the problem with nested comprehensions? How else do you create bi-dimensional stuff?
by enriquto 6y ago
What's the problem with nested comprehensions? How else do you create bi-dimensional stuff?
- magnusmundus 6y agoNot the same kind of nesting, is it? [[None for _y in range(y)] for _x in range(x)] for two dimensions is fine, while [None for _x in range(x) for _y in range(y)] (to create a flattened 2-dim list? excuse the dummy example) is just begging for later headache. Explicit looping is much more readable. Note the flipped order of expressions -- these two statements create the same iterators. Not to mention, you can even reuse the name for extra evil: [i for i in range(2) for i in range(3)] results in [0, 1, 2, 0, 1, 2]
- joshuamorton 6y agoFwiw, I find creating a 2d array and then flattening (`itertools.chain.from_iterable([[None for _y in range(y)] for _x in range(x)])` to be both readable and reasonably concise, though yes explicit loops are also fine.
- cat199 6y agonice trick.. though if you are relying on the 'generator' aspect of comprehensions this may be problematic (will create in-memory copies)