Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting a string inside a list n times ie list of a list of a list

def nest(x, n):
    a = []
    for i in range(n):
        a.append([x])
    return a

print nest("hello", 5)

This gives an output

[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

The desired output is

[[[[["hello"]]]]]
like image 697
Boa Avatar asked Feb 05 '23 22:02

Boa


2 Answers

Every turn through the loop you are adding to the list. You want to be further nesting the list, not adding more stuff onto it. You could do it something like this:

def nest(x, n):
    for _ in range(n):
        x = [x]
    return x

Each turn through the loop, x has another list wrapped around it.

like image 193
khelwood Avatar answered Feb 08 '23 15:02

khelwood


instead of appending you sould wrap x and call recursively the method till call number is lesser than n

def nest(x, n):
    if n <= 0:
        return x
    else:
        return [nest(x, n-1)]
like image 37
m.antkowicz Avatar answered Feb 08 '23 14:02

m.antkowicz