Python - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'? What am i doing wrong?

3.5k Views Asked by At

I am trying to create a Python definition to display a list and trying to add a feature where if the list is more than 10 it will display it horizontally.

Here's my code:

def print_vert_list(list):
index = 0
for i in list:
    if len(list) > 10:
        print (" ".join(list[index]) + " ".join(list[11:11+index])) + " ".join(list[21:21+index])
    else:
        print (" ".join(list[index]))
        index += 1

And here's the log:

Traceback (most recent call last):
File "**********", line 30, in <module>
print_vert_list(file_var_list)
File "**********", line 22, in print_vert_list
print (" ".join(list[index]) + " ".join(list[11:11+index])) + " ".join(list[21:21+index])
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
5

There are 5 best solutions below

0
On

If I understand correctly the question then this is a solution:

def print_vert_list(list_items):
    if len(list_items) > 10:
        for i in list_items:
            print(i, end=' ')
    else:
        for i in list_items:
            print(i)
0
On

You must have an element contained in the list where it is not a string. The error message is telling you that the program is breaking because you are trying to concatenate a None type with a string type. For example:

a = "string1" + "string2" print(a) # will give you string1string2

But if you try a = None + "string1" # You will get the same error message

Using this logic, you can add a conditional check to make sure that the element of the list is not of None type, then you could successfully concatenate it

0
On

print() returns None. You cannot add a string to the result of a call to print as you cannot add None and a string

print(" ".join(list[index]) + " ".join(list[11:11+index])) + " ".join(list[21:21+index])
                                   end of the print call ^ ^ You cannot add a string here
0
On

The + operator is only defined for strings (...and numbers however in another context...)

In line print (" ".join(list[index]) + " ".join(list[11:11+index])--->>>)<<<--- + " ".join(list[21:21+index]) is a wrong parenthesis. Print function returns NoneType and because of this additonal parenthesis the intepreter thinks that the print statement ends here. So this additional parenthesis causes the same behavior like described in Python 3.3 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' and so throws the same error

0
On

Your parentheses are wrong in that line. You would want:

print (" ".join(list[index]) + " ".join(list[11:11+index]) + " ".join(list[21:21+index]))

instead of:

print (" ".join(list[index]) + " ".join(list[11:11+index])) + " ".join(list[21:21+index])

which gives you an error because you try to add a string to the return value of print.