0
'''
[[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]
find 1
'''
key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

#len(x) -> 1 

Actually my question is simple, but i couldn't solve this problem... What should i use to solve it, i mean should i use recrusive functions or for loop ???

for i in range(len(x)):
    for j in range(len(x)):
        for k in range(len(x)):
            for _ in range(len(x)):
                for ... 
4
  • What is your question though? What does "extract list" mean? Commented Nov 1, 2022 at 12:54
  • "this problem" what problem? You just posted a bunch of nonsense code, not a problem. Commented Nov 1, 2022 at 12:54
  • 1
    What is a recrusive function? Commented Nov 1, 2022 at 13:07
  • take a look programiz.com/python-programming/recursion Commented Nov 1, 2022 at 13:15

4 Answers 4

2

You can do that as follow using more_itertools

import more_itertools

key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

flattened_list = list(more_itertools.collapse(x))

print(flattened_list) # [1]
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a non-recursive approach for your current structure:

def extract_list(l: list):
    while True:
        l = l.pop()
        if not isinstance(l, list):
            return l


x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]
print(extract_list(x))  # 1

Comments

1

You can also do it with type check

key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def find_key(array):
    if type(array) is list:
        return find_key(array[0])
    return array

print(find_key(x))

Comments

0

You could do this a couple ways but here's a solution using recursion:

x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def find_num(l):
    if isinstance(inner := l[0], list):
        return find_num(inner)
    return inner

print(find_num(x))

1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.