How to build a list recursively given only the length?

Viewed 149

I am trying to write a recursive function that takes a number n and some value, let's say 'a', and recursively builds a list made up of n 'a's.

So, func(4, 'a') returns ['a','a','a','a'].

My internet searches so far have been surprisingly futile. Most examples of list recursion I have found take additional parameters.

I have tried various versions of the following code:

def func(n, a):
    if n == 1:
        return [a]
    else:
        return func(n-1, a).append(a)

I keep getting cannot append to NoneType errors on that last return. So func(n-1,a) is returning None.

3 Answers

list.append only returns None as its purpose is to update the target list in-place. Instead of appending, simply add:

def func(n, a):
   if n == 1:
      return [a]
   else:
      return func(n-1, a) + [a]

print(func(4, 'a'))

Output:

['a', 'a', 'a', 'a']

Additionally, you may want to consider using generators to provide a cleaner (and shorter) result:

def func(n, a):
  if n:
    yield a
    yield from func(n-1, a)

print(list(func(4, 'a')))

Output:

['a', 'a', 'a', 'a']

Does it have to be recursive?

def func(n, a): a_list = [] for i in range(n): a_list.append(str(a)) return a_list

Because the list.append method returns None you have to do it this way if you want to use the append method:

def func(n, a):
    if n == 1:
        return [a]
    else:
        temp = func(n-1, a)
        temp.append(a)
        return temp

print(func(5, 'a'))

Prints:

['a', 'a', 'a', 'a', 'a']
Related