2

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.

yudai-nkt
  • 262
  • 2
  • 8
  • Isn't it podsible to just pass the inner list to the `VarList` initializer? – CristiFati Oct 11 '17 at 17:08
  • That's... not how unpacking works. First, the unpacking in `(*nested_list,)` doesn't help you; the `[0]` is doing all the useful work there. Second, for your desired unpacking to work, you'd have to create a `VarList`, not a `list`, and there's no syntactical support for doing that. There may be not-unpacking ways to do what you want, depending on the details of VarList and exactly what you want to preserve. – user2357112 Oct 11 '17 at 17:20

2 Answers2

1

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)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • I'm afraid I don't understand why `nested_list = ...` yields different result (i.e., a list object). Is it related to list mutability? – yudai-nkt Oct 12 '17 at 07:05
  • 1
    Maybe [this answer](https://stackoverflow.com/a/10623383/8747) will help explain the difference between `nested_list = ...` and `nested_list[:] = ...` – Robᵩ Oct 12 '17 at 16:18
  • Thanks for the reference! – yudai-nkt Oct 28 '17 at 10:29
1

Yes, that's possible with a slice assignment:

>>> nested_list = [[1, 2]]
>>> id(nested_list)
140737100508424
>>> nested_list[:] = nested_list[0]
>>> id(nested_list)
140737100508424
wim
  • 338,267
  • 99
  • 616
  • 750