-2

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?

brtt
  • 1
  • 2

3 Answers3

1

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]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

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]
AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    This is not a general solution. It only works in this narrow case. – dawg Nov 21 '21 at 20:15
  • 1
    @dawg But I guess it's the flaw of the question. The question was not clear enough how general the solution is expected. To me it is fairly general (in terms of the depth of nests), given the question. It is the question what is to be blamed. – j1-lee Nov 21 '21 at 20:23
  • Agreed. That is why I originally closed it but then saw that there was a pony in there... – dawg Nov 21 '21 at 20:29
0

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]
>>> 
dawg
  • 98,345
  • 23
  • 131
  • 206