How to fix "TypeError: 'NoneType' object is not subscriptable"?

Question:

I’ve started going through Udacity course Intro to Computer Science and I’ve come up against following problem:
Define a procedure that takes in a string of numbers from 1-9 and
outputs a list with the following parameters:
Every number in the string should be inserted into the list.
If a number x in the string is less than or equal
to the preceding number y, the number x should be inserted
into a sublist. Continue adding the following numbers to the
sublist until reaching a number z that
is greater than the number y.
Then add this number z to the normal list and continue.

I’ve found this solution, which works without problem:

def numbers_in_lists(theString):
    maxNum = int(theString[0])
    mainList = [maxNum]    
    for e in theString[1:]:
        num = int(e)
        if num > maxNum:
            mainList.append(num)
            maxNum = num
        else:
            if (type(mainList[-1]) == list):
                mainList[-1].append(num)
            else:
                mainList.append([num])              
    return mainList

This is my code.

def numbers_in_lists(s):
    p = [int(s[0])]
    n = len(s)
    i = 1
    while i < n:
        first = int(s[i-1])
        second = int(s[i])
        if (second > first): p = p.append(second)
        if (second <= first):
            if (type(p[-1]) == list): p[-1].append(second)
            else: p.append([second])
        i = i + 1
    return p

It’s similar, apart from while loop. I get an error

line 10, in numbers_in_lists
    if (type(p[-1]) == list): p[-1].append(second)
TypeError: 'NoneType' object is not subscriptable

I get the solution, but I don’t understand why my code isn’t working and how to fix the error.

Asked By: clueless

||

Answers:

This is the problem:

if (second > first): p = p.append(second)

The append() method modifies the original list; it doesn’t return a new list. It returns None.

Just use p.append(second).

Answered By: John Gordon
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.