What I'm trying to do is a list with an arbitrary number of other nested lists, recursively descending through the last value in the nested lists, until I reach the maximum depth, and then add the value to this list. An example might make this clearer:
>>> nested_list1 = [1, 2, 3, [4, 5, 6]] >>> last_inner_append(nested_list1, 7) [1, 2, 3, [4, 5, 6, 7]] >>> nested_list2 = [1, 2, [3, 4], 5, 6] >>> last_inner_append(nested_list2, 7) [1, 2, [3, 4], 5, 6, 7]
The following code works, but it seems too complicated to me:
def add_to_inner_last(nested, item): nest_levels = [nested] try: nest_levels.append(nested[-1]) except IndexError: # The empty list case nested.append(item) return while type(nest_levels[-1]) == list: try: nest_levels.append(nest_levels[-1][-1]) except IndexError: # The empty inner list case nest_levels[-1].append(item) return nest_levels[-2].append(item) return
Some things I like:
- Works
- It handles row cases at the end of lists and cases of empty lists.
Some things I don't like:
- I need to check the type of objects because rows are also indexed
- The indexing system seems too magical - I won’t be able to figure it out tomorrow.
- It feels too smart to use the fact that adding to a link list affects all links
Some common questions that I have:
- At first I was worried that adding to
nest_levels was ineffective, but then I realized that this was probably just a link, and a new object was not created, right? - This code is a purely side effect (it always returns
None ). Should I be bothered by this?
Basically, although this code works (I think ...), I wonder if there is a better way to do this. For the better, I mean clearer or more pythonic. Potentially something with more explicit recursion? I was not able to determine a breakpoint or a way to do this without side effects.
Edit:
To be clear, this method should also handle:
>>> last_inner_append([1,[2,[3,[4]]]], 5) [1,[2,[3,[4,5]]]]
and
>>> last_inner_append([1,[2,[3,[4,[]]]]], 5) [1,[2,[3,[4,[5]]]]]