Home > Software engineering >  How to unpack values from a list stored inside another list
How to unpack values from a list stored inside another list

Time:01-13

I have a list containing some elements, a lit and some other elements like so [a, b, [c, d, e], f, g] and I would like to get [a, b, c, d, e, f, g]. I tried using itertools which I'm not familiar with, but I was unsucessfull:

from itertools import chain

a = 1
b = 2
c = [3, 4, 5]
d = 6
e = 7

list(chain(a, b, c, d, e))

It throws a TypeError

Any help is appreciated!

CodePudding user response:

you could convert from a list mixed of lists and ints to a list strictly of lists, and then apply itertools chain.

from itertools import chain

l1= [1,2,[3,4,5],6,7]
l2 = list(chain.from_iterable(i if isinstance(i, list) else [i] for i in l1))

Or check the type and then extend or append the new list;

l1= [1,2,[3,4,5],6,7]    
l2 = []
for i in l1:
    l2.extend(i) if isinstance(i, list) else l2.append(i)

CodePudding user response:

If you want a function that takes an arbitrary number of arguments, you could use the below solution

First I convert all input arguments to lists arg if isinstance(arg, list) else [arg], and then I use a "trick" with the summation function to flatten the lists.

def unpacker(*args):
    return sum([arg if isinstance(arg, list) else [arg] for arg in args], [])

Example

a = 1
b = 2
c = [3, 4, 5]
d = 6
e = 7

print(unpacker(a, b, c, d, e))
>>> [1, 2, 3, 4, 5, 6, 7]
  • Related