Skip to content
Advertisement

alternately flatten values of nested list

Is there a way to flatten values of a nested list but alternately?

example:

nested_list = [[1, 3, 5], [2, 4]]

my expected output would be:

[1, 2, 3, 4, 5]

Advertisement

Answer

You can do it without numpy using iterators and keep track when the list stops growing:

nested_list = [[1, 3, 5], [2, 4]]

# create a list of iterators per sublists
k = [iter(sublist) for sublist in nested_list]

# collect values
res = []

# choose a value thats not inside your lists
sentinel = None

growing = True
while growing:
    growing = False
    for i in k:
        # returns sentinel (None) if sublist no longer iterable
        u = next(i, sentinel)

        # add if it got a value
        if u != sentinel:
            growing = True
            res.append(u)
        
print(res)  # [1,2,3,4,5]

IF you have None values in your list, you need to choose another sentinel value.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement