I wrote a program which gets a number n ( > 0) and prints all the numbers with n digits.

def Q(n, index = 0, list = []):

        if (index == n):
                print list
                return

        startFrom = 0
        if (index == 0 and n > 1):
                startFrom = 1

        for i in range(startFrom, 10):
                list.append(i)
                Q(n, index + 1, list)
                list = list.__delitem__(index)

Q(2)

When I run the code, I get:
[1, 0]

Traceback (most recent call last):
File "py_Q.py", line 16, in ?
Q(2)
File "py_Q.py", line 13, in Q
Q(n, index + 1, list)
File "py_Q.py", line 12, in Q
list.append(i)
AttributeError: 'NoneType' object has no attribute 'append'

After the program prints the first number (as list), the list becomes NonType.

Could someone explain me what's happening here???

Thanks in advance!

Recommended Answers

NoneType means that delitem deletes in place so
list.__delitem__(index)
works for your code, and
list = list.__delitem__(index)
binds "list" to the return value=None. Also, choose a name other than "list" as that is already used by Python to convert to a list.

Jump to Post

All 2 Replies

OK. I solved it.
Instead of using __delitem__ I just used the pop function.

I still need a good explanation, because I want to understand the principals that caused my program to fail.

NoneType means that delitem deletes in place so
list.__delitem__(index)
works for your code, and
list = list.__delitem__(index)
binds "list" to the return value=None. Also, choose a name other than "list" as that is already used by Python to convert to a list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.