954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

List becomes 'NoneType' object

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!

neti1987
Newbie Poster
24 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

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.

neti1987
Newbie Poster
24 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

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.

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: