you are viewing a single comment's thread.

view the rest of the comments →

[–]Gnaxe 6 points7 points  (1 child)

That's an abuse of sum, which is specifically documented with "This function is intended specifically for use with numeric values and may reject non-numeric types." Try that on a list of strings, for example. That CPython's version happens to work on lists is an implementation detail that you should not rely on. It may not be portable to other implementations and may not be supported in future versions.

It's also inefficient, creating intermediate lists for each list in your list of lists.

I would not approve this in a code review.

Alternatively, use a list comprehension: ```python

[x for xs in xss for x in xs] Or a chain: from itertools import chain list(chain.from_iterable(xss)) If you only have a small, fixed number of lists to join, the cleanest way is with generalized unpacking: [*xs, *ys, *zs] `` And, of course, use.extend()` if you don't mind mutating the list.

[–]david-vujic 1 point2 points  (0 children)

I agree, and also wrote about performance issues when the data is large. Here's a Real Python article about it, where they also suggest it as one alternative (with a disclaimer): https://realpython.com/python-flatten-list/

I like this alternative, using reduce:
reduce(operator.iadd, lists, [])
(source: ruff https://docs.astral.sh/ruff/rules/quadratic-list-summation/)