How to extract non-empty elements from python for number list

Question:

I currently have a list that looks like this:

[
    [0], [2], [4], [6], [7], [9], [20], [24],
    [], [26], [], [27], [], [], [], [],
    [], [], [], [], [], [], [], [],
    [], []
] 

How can I transform it to look like [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]?

Asked By: youtube

||

Answers:

Assuming list1 the input list, use itertools.chain:

from itertools import chain

out = list(chain.from_iterable(list1))

output: [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]

Answered By: mozway

Just use a list comprehension:

out = [l[0] for l in list1 if len(l) > 0]
Answered By: Eelco van Vliet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.