0

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

itamar kanter
  • 1,170
  • 3
  • 10
  • 25
  • 1
    Honestly, this code is already pretty clear. A comprehension might arguably be more idiomatic, but I think I'd stick with something similar to what you already have. The only issue I see is it's easy to miss the `append`/`extend` difference. – Carcigenicate Jun 13 '21 at 16:37

1 Answers1

2

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]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 2
    Beat me to it. Although I must say that personally I do not think this is very readable - but it is what OP requested. Also, isinstance of `Iterable` might be the more general solution here (from ABC). – Bram Vanroy Jun 13 '21 at 16:38