1

I have a list of lists like this,

sm = [['123'],['456'],['789'],[],['101']]

then I flatten the list,

sm_flattened = [val for sublist in sm for val in sublist]

Now, I get this (sm_flattened),

['123', '456', '789', '101']

However, I need my sm_flattened like this,

['123', '456', '789', '', '101']

How can I get this? Any suggestions would be nice!

1 Answer 1

4

In order to do that, you'll need to transform your empty sublist in a sublist with an empty string inside.

One alternative would be:

sm_flattened = [val for sublist in sm for val in (sublist or [''])]

It basically uses [''] instead of sublist in case sublist is empty for that iteration.

Sign up to request clarification or add additional context in comments.

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.