How to convert list list to single list without import

My list:

a = [[1,2], [23,51,6], ["Hi", "hello"]]

I want to release:

a = [ 1,2,23 51,6, "Hi", "hello"]
+4
source share
3 answers

Using list comprehension :

>>> a = [[1,2], [23,51,6], ["Hi", "hello"]]
>>> [x for xs in a for x in xs]
[1, 2, 23, 51, 6, 'Hi', 'hello']
+4
source

Use sumwith two arguments, a list of lists, and an empty list to add:

>>> sum(a, [])
[1, 2, 23, 51, 6, 'Hi', 'hello']

what really is a special case reduce:

>>> reduce(list.__add__, a)
[1, 2, 23, 51, 6, 'Hi', 'hello']

, , Guido reduce Python 3 , ( ). sum , reduce . Python 3 reduce.

, itertools.chain, , . list, :

>>> import itertools
>>> list(itertools.chain(*a))
[1, 2, 23, 51, 6, 'Hi', 'hello']
+1

itertools.chain.from_iterable:

>>> from itertools import chain
>>> a = [[1,2], [23,51,6], ["Hi", "hello"]]
>>> list(chain.from_iterable(a))
[1, 2, 23, 51, 6, 'Hi', 'hello']

, .

0

Source: https://habr.com/ru/post/1525360/


All Articles