-3

I have a list of lists that looks as follows (I hope I'm right when I said list of lists):

['[175', '178', '182', '172', '167', '164]', "['b']"]

How can I concatenate the two lists? That is, having a list that looks as follows:

[175, 178, 182, 172, 167, 164, b]

Any thoughts?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

3 Answers3

3

First, note that that's not a list of lists, but just a list of strings that, when concatenated, might look like one or more (nested) lists, in particular with those [ and ] in the first and last element. Thus, you could join those strings with , to a string that actually represents a pair or tuple of lists, and then eval or ast.literal_eval those. Then just use a list comprehension to flatten that actual list of lists.

>>> lst = ['[175', '178', '182', '172', '167', '164]', "['b']"]

>>> ','.join(lst)
"[175,178,182,172,167,164],['b']"

>>> ast.literal_eval(','.join(lst))
([175, 178, 182, 172, 167, 164], ['b'])

>>> [x for sub in ast.literal_eval(','.join(lst)) for x in sub]
[175, 178, 182, 172, 167, 164, 'b']
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

list concatenations work with a + so ...

lsts = ['[175', '178', '182', '172', '167', '164]', "['b']"]
new_lsts = []
for i in lsts:
  new_lsts += i

Also this similar question has been asked here many times.

Here

and here

and probably several other times

Rohan D'Souza
  • 67
  • 1
  • 5
-1

In python you can use + to concat them:

a = [2,5,6]
b = [6,1,4]
c = a+b
print(c)
BladeMight
  • 2,670
  • 2
  • 21
  • 35