-1

For example, I'm having this: a = [['1'], ['2'], ['3']]

How can I change it into: a = ['1', '2', '3']

Thanks!

  • 1
    `list(itertools.chain.from_iterable(a))` – Netwave Nov 16 '18 at 10:52
  • 1
    `a = np.array(a).squeeze()` or `[l[0] for l in a]` – Silver Nov 16 '18 at 10:52
  • @SilverSlash, there is no `numpy` tag ;) – Netwave Nov 16 '18 at 10:53
  • 1
    You have a list of lists, and it appears that you want a list. But the square brackets aren't really unnecessary, because that is how you represent a list of lists. So your question is really "How do I flatten a list of lists into a single list containing the elements of all the sublists?" And as you can see from the comments and answers, there are a lot of ways to do that. – BoarGules Nov 16 '18 at 10:56

2 Answers2

1

ooh, i'll play.

a = [i[0] for i in a]

(assuming you only have one item in each sublist)

Stael
  • 2,619
  • 15
  • 19
0

Like so:

a = [['1'], ['2'], ['3']]
lst = []
for subLst in a:
    lst.extend(subLst)
print(lst)

But in most cases this means that the generation of the list a get improved ...

quant
  • 2,184
  • 2
  • 19
  • 29