Home > Mobile >  How to access the last list in a list
How to access the last list in a list

Time:11-22

So let's say I have the following list.

[1,2,[3,4,5,6,[7,8,[9]]]]

Is there an easy way to access the list [9] without doing a function?

CodePudding user response:

Lambdas are functions with another syntax, so this answer might not be what you really want, but

>>> x = [1,2,[3,4,5,6,[7,8,[9]]]]
>>> z = lambda x: z(x[-1]) if len(x) > 1 else x
>>> z(x)
[9]

CodePudding user response:

Suppose you have:

li=[1,2,[3,4,5,6,[7,8,[9,10]]]]

You can use a recursive function to find the last list:

def flatten(L):
  last_list=[]
  for item in L:
    try:
      last_list.append(item)
      yield from flatten(item)
    except TypeError:
      yield last_list

Then just exhaust the generator and the last one is the last list:

>>> for l in flatten(li): pass
>>> l
[9,10]
>>> 

CodePudding user response:

You could use a while loop:

L  = [1,2,[3,4,5,6,[7,8,[9]]]]

lastList = L
while isinstance(lastList[-1],list): 
    lastList = lastList[-1]

print(lastList)
[9]
  • Related