itamar kanter
itamar kanter

Reputation: 1360

Flattening a list of mixed iterable and non-iterable objects

Yes, I know this topic has been covered before here but my question is concentrating in the case where the list has a maximal depth of 2 (i.e has objects of type list or int)

I have a list composed of iterable (i.e. lists) and non-iterable objects (i.e. integers) and I want to unpack all the iterable objects. Here is an example of the functionality I'm trying to implement:

list_of_items = [[0, 1], 2, 3]
flatten_list = []
for x in list_of_items:
    if hasattr(x, '__iter__'):
        flatten_list.extend(x) 
    else:
        flatten_list.append(x)
print(flatten_list)

output:

[0, 1, 2, 3]

I'm looking for a more pythonic way or elegant one-liner solution with equivalent functionality

Upvotes: 0

Views: 121

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195448

With your constraints (max 2 level depth, only list of int/list) you can do:

out = [v for i in list_of_items for v in (i if isinstance(i, list) else [i])]
print(out)

Prints:

[0, 1, 2, 3]

Upvotes: 2

Related Questions