'How to flatten a list containing lists and not lists: [duplicate]

Since stackoverflow refuses to let me answer this question as I'm a new user, I'll post my question and answer here. (The question is not present in the list of "Similar questions," either.)

QUESTION:

How can I flatten the following list of lists and ints?

[0, 10, [20, 30], 40, 50, [60, 70, 80]]



Solution 1:[1]


lst = [0, 10, [20, 30], 40, 50, [60, 70, 80]]

new_lst = []
for a in lst:
    if type(a)!=list:
        new_lst.append(a)
    else:
        new_lst.extend(a)

print(new_lst)

OUTPUT

[0, 10, 20, 30, 40, 50, 60, 70, 80]

Below is working even if the input list also contains float, tuple and string.

lst = [1,2,[3,4],"hello world"]

new_lst = []
for a in lst:
    if isinstance(a,int) or isinstance(a,float) or isinstance(a,str):
        new_lst.append(a)
    else:
        new_lst.extend(a)

print(new_lst)

OUTPUT

[1, 2, 3, 4, 'hello world']

Solution 2:[2]

V1 -- works for a list of lists, ints, strings:

def FlattenAllItems(lst):
    if not lst: return []
    flattened = []
    for item in lst:
        if type(item) != list:
            item = [item]
        for i in item:
            flattened.append(i)
    return flattened

V2 -- adds ability to unpack a tuple, as well:

def FlattenAllItems(lst):
    if not lst: return []
    flattened = []
    for item in lst:
        if type(item) == tuple:
            item = [*item]
        if type(item) != list:
            item = [item]
        flattened.extend(item)
    return flattened

Thanks for reading!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 It's All Waves