-1

I have a list with a list inside.

Can you please help me - how to change the list of lists to list?

I tried with nd.array reshape(), flatten(), and ravel(), but no luck

Input:

['Test', [1, 2]]

Expected result:

['Test', 1, 2]
petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    [`more_itertools.flatten`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten) is another option. – 0x5453 Aug 15 '22 at 17:50
  • 1
    `I tried with nd.array reshape(), flatten(), and ravel(), but no luck` what do you mean no luck? What exactly did you try? What happened? Was there an error? Is your starting list a basic Python `list` or is it an `ndarray`? If it's an `ndarray` I assume your `dtype` is `object`, so that you don't get errors trying to store strings and numbers in the same list, right? – Random Davis Aug 15 '22 at 17:50
  • Please add more information. What happened when you tried those numpy solutions? – jkr Aug 15 '22 at 18:26
  • Does this answer your question? [How do I flatten a list of lists/nested lists?](https://stackoverflow.com/questions/20112776/how-do-i-flatten-a-list-of-lists-nested-lists) – Daniel Hao Aug 15 '22 at 20:14

3 Answers3

1

This problem is known as flattening an irregular list. There are a few ways you can do this -

Using list comprehension

l = ['Test', [1, 2]]

regular_list = [i if type(i)==list else [i] for i in l]
flatten_list = [i for sublist in regular_list for i in sublist]
flatten_list
['Test', 1, 2]

Using nested for loops

out = []
for i in l:
    if type(i)==list:
        for j in i:
            out.append(j)
    else:
        out.append(i)
print(out)
['Test', 1, 2]
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

There are multiple answers, depending on context and preference:

For python lists:

flattened_list = [element for sublist in input_list for element in sublist]

# or:

import itertools

flattened_list = itertools.chain(*input_list)

Or, if you are using numpy.

flattened_list = list(original_array.flat)

# or, if you need it as a numpy array:

flattened_array = original_array.flatten()
Euklios
  • 387
  • 1
  • 12
0

You can try this:

li = ['Test', [1, 2]]

merged = []
for x in li:
  if not isinstance(x, list):
    merged.append(x)
  else:
    merged.extend(x)

print(merged)

Output: ['Test', 1, 2]

Moid
  • 410
  • 5
  • 9