4

Very popular answer but my one differs from others. I have a list:

s = [(1, 2, 3),
     (4, 5, 6),
     (7, 8, 9)]

I need without another lists combine my lists inside and make one big list. I need them to be string so I do

[map(str, x) for x in s]

But in this way I get [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

So I need ['1', '2', '3', '4', '5', '6', '7', '8', '9']

  • 11
    Possible duplicate of [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – ndmeiri Feb 27 '18 at 08:13

6 Answers6

2

You need list comprehension with flatenning:

print ([i for x in s for i in map(str, x)])
['1', '2', '3', '4', '5', '6', '7', '8', '9']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2
import itertools
s = [(1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)]
print(list(map(str,itertools.chain(*s))))
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
1

You can use sum and list:

map(str, list(sum(s, ())))
Maroun
  • 94,125
  • 30
  • 188
  • 241
1

Simply using a nestled list comprehension is perhaps the easiest

>>> [str(sii) for si in s for sii in si]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
1

Another option is to use reduce to make the flat list and map to cast elements to string.

>>> from functools import reduce

>>> s = [(1, 2, 3), (4, 5, 6),(7, 8, 9)]
>>> list(map(str,reduce(lambda x,y: x+y,s)))
>>> ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
1

itertools.chain is convenient for this purpose:

from itertools import chain

s = [(1, 2, 3),
     (4, 5, 6),
     (7, 8, 9)]

list(map(str, chain.from_iterable(s)))

# ['1', '2', '3', '4', '5', '6', '7', '8', '9']
jpp
  • 159,742
  • 34
  • 281
  • 339