Search code examples
pythonpython-3.xlistiterable-unpacking

How to unpack inner lists of a nested list?


Suppose we have a nested list like nested_list = [[1, 2]] and we want to unpack this nested list. It can easily be done with the following (although this requires Python 3.5+):

>>> nested_list = [[1, 2]]
>>> (*nested_list,)[0]
[1, 2]

However, this operation unpacks the outer list. I want to strips off the inner brackets but I haven't succeeded. Is it possible to do such kind of operation?

The motivation might be unclear with this example, so let me introduce some background. In my actual work, the outer list is an extension of <class 'list'>, say <class 'VarList'>. This VarList is created by deap.creator.create() and has additional attributes that the original list doesn't have. If I unpack the outer VarList, I lose access to these attributes.

This is why I need to unpack the inner list; I want to turn VarList of list of something into VarList of something, not list of something.


Solution

  • If you want to preserve the identity and attributes of your VarList, try using the slicing operator on the left-hand side of the assignment, like so:

    class VarList(list):
        pass
    
    nested_list = VarList([[1,2]])
    nested_list.some_obscure_attribute = 7
    print(nested_list)
    
    # Task: flatten nested_list while preserving its object identity and,
    # thus, its attributes
    
    nested_list[:] = [item for sublist in nested_list for item in sublist]
    
    print(nested_list)
    print(nested_list.some_obscure_attribute)