0

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]
4
  • 1
    more_itertools.flatten is another option. Commented Aug 15, 2022 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? Commented Aug 15, 2022 at 17:50
  • Please add more information. What happened when you tried those numpy solutions? Commented Aug 15, 2022 at 18:26
  • Does this answer your question? How do I flatten a list of lists/nested lists? Commented Aug 15, 2022 at 20:14

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.