ponir ponir - 1 month ago 9
Python Question

Converting 2D String array into 1D String array in Python

I have a string array that looks like this:

string = [ [ "this is a sample",
"this is another sample"],
[ "The third sample",
"the fourth one"] ]


But I want to convert it to:

string = [ "this is a sample",
"this is another sample",
"The third sample",
"the fourth one" ]


How can I do it?
I know I can do it by pre-allocating a string and iterating. But is there a simpler method?

Answer

You can try like this using list comprehension. Code:

string = [ [ "this is a sample",
         "this is another sample"],
       [ "The third sample",
         "the fourth one"] ]

print([_ for i in range(len(string)) for _ in string[i]])
Comments