Unsupported operand type s for int and list ошибка

I am trying to do a project in python. I’m getting an error in the line

s+=line

TypeError: unsupported operand type(s) for +=: 'int' and 'list'

Here is the function called testIfCorrect:

def testIfCorrect(world, x, y):
    s=0
    for line in world:
        s+=line
        print("ligne",line)
        if(s > 2):
            return False
    for i in range(x):
        if(sum(returnColumn(world, i)) > 2):
            return False
    for j in range(x):
        for k in range(y):
            if(j == k):
                pass
            else:
                if(world[j] == world[k]):
                    return False
                if(returnColumn(world, j) == returnColumn(world ,k)):
                    return False

def returnColumn(array, column):
    return [col[column] for col in array]

Where is the error?

Sakib Ahammed's user avatar

asked Sep 12, 2015 at 19:00

Julien Martin's user avatar

2

In

s=0
for line in world:
    s+=line

Here s is an int and wordis 2D List. So, In for line in world, line is a 1D List. It is impossible to add a List into a int type. Here, s+=line in incorrect

So, In s+=line, you can replace s+=sum(line). I think you have found your answer.

Try this:

s=0
for line in world:
    s+=sum(line)

answered Sep 12, 2015 at 19:24

Sakib Ahammed's user avatar

Sakib AhammedSakib Ahammed

2,4522 gold badges24 silver badges29 bronze badges

1

Python provides multiple operators to perform specific calculations on the variables and values in the program. All the operators in Python follow specific operand types and will give an error if the operand is unsupported. For instance, the addition operator can not be placed between operands like “int” and “list”. To resolve such types of errors, various methods are provided by Python.

This write-up will provide a comprehensive guide on resolving the “unsupported operand type(s) for +:int and list” error using various solutions. The contents to be discussed in this article are listed below:

  • Reason 1: Using Addition Operator With Number and List
  • Solution 1: Use Simple for Loop
  • Solution 2: Use List Comprehension
  • Solution 3: Access Specific Items in the List

So, let’s get started with the first reason.

Reason 1: Using Addition Operator With Number and List

The “unsupported operand type(s) for +: int and list” error appears in Python when a user tries to add an integer to the list using the addition operator “+”. Here is an example:

The above output shows the “TypeError” because the integer “45” is added to the list “list_value” using the addition operator “+”.

Solution 1: Use Simple for Loop

The error will be fixed using a simple “for” loop that will iterate over the list element and add the specified integer “6” into each list element. The example code is given below:

Code:

list_value = [44, 23, 45]
empty_list = []
for item in list_value:
    empty_list.append(item + 6)
print(empty_list)

In the above code:

  • The list named “list_value” and the empty list named “empty_list” is created in the program.
  • The “for” loop iterates over the list items, and on each iteration, the integer value “6” has been added to the list element using the “append()” function.

Output:

The above output verified that an integer value had been added to each list element.

Solution 2: Use List Comprehension

The other solution to resolve this error in Python is using “List Comprehension” along with the “for” loop. The List comprehension method has similar functionality to the above “for” loop method. As a single-line statement code, this method can compact the program.

Code:

list_value = [44, 23, 45]
list_a = [i + 6 for i in list_value]
print(list_a)

In the above code:

  • The list comprehension has a “for” loop that iterates over the list and adds each element of the list using the “+” operator.
  • The final output list “list_a” has been displayed on the screen utilizing the “print()” function.

Output:

This output shows that each element has been added to an integer “6”.

Solution 3: Access Specific Items in the List

We can also add the elements of the “list” and “int” using an addition operator by accessing specific items in the list. This method does not add all the list items to an integer; instead, it adds only a specific list element with the given integer value.

Code:

list_value = [44, 23, 45]
output = 56 + list_value[0]
print(output)

In the above code:

  • The “list_value[0]” is used to get the list value placed at index position “0” which is “44”.
  • After that, the integer value “56” has been added to a specific index value using the addition operator “+”.

Output:

The above output calculates the integer value and list value successfully using a specific index value.

These are all the reasons and solutions to fix this TypeError.

Conclusion

The “TypeError: unsupported operand type(s) for +:int and list” occurs when a user uses the addition operator “+” to add integers and lists. To resolve this error, various solutions are used in Python, such as using “for” Loop, using List Comprehension, and accessing specific items in the list. The “for” loop and list comprehension method have similar functionality, i.e., adding integer values to each list element. This article presented a detailed guide on rectifying Python’s “unsupported operand type(s) for +:int and list” error.

In this article, we will discuss the possible causes of Typeerror unsupported operand type s for int and list, and provide solutions to resolve the error.

But first, let’s discuss What this error means.

The error message “unsupported operand type s for int and list” means that you are trying to operate on an integer and a list that is not allowed.

The “unsupported operand” part of the error message refers to the specific operation you are trying to perform, such as addition or subtraction

So why this TypeError occurs?

Why Typeerror unsupported operand type s for int and list Occurs?

The main reason why “Typeerror unsupported operand type s for int and list” occurs is when you are trying to add, subtract, divide, or minus a list to an integer using the +,-, *, or / operators.

These operators do not support performing arithmetic operations between a list and a number.

For Example:

list_num = [1, 2, 3, 4, 5]
sum_num = 1 + list_num
print(sum_num)

In this example, The Typeerror Triggers because we are trying to perform an operation between an integer (1) and a list (list_num).

Specifically, the + operator in 1 + list_num is trying to add an integer and a list, which is not supported in Python.

Expected Output:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

Now let’s fix this error.

Typeerror unsupported operand type s for int and list – Solutions

Here are the alternative solutions that you can use to fix “unsupported operand type s for int and list” error:

Solution 1. Use simple for loop

By using a for loop, we perform the desired operation on each element in the list.

Here’s an Example snippet code:

my_list = [1, 2, 3, 4, 5]
my_number = 2
result = []

for num in my_list:
    result.append(num + my_number)

print(result)

In this code, we define a list called my_list and a number called my_number.

We then create an empty list called result.

Next, we use a for loop to iterate over each element in my_list.

On each iteration, we add my_number to the current element and append the result to the result list.

Finally, we print the contents of the result list, which should contain the result of adding my_number to each element in my_list.

Output:

[3, 4, 5, 6, 7]

Solution 2. Use List Comprehension

List comprehension is a concise and elegant way to create a new list from an existing list or any other iterable object in Python.

It allows you to write a one-liner code that performs some operation on each element of the iterable object and creates a new list from the results.

Here’s an example of how to use list comprehension to fix the error:

my_list = [1, 2, 3, 4, 5]
my_number = 2

result = [num + my_number for num in my_list]
print(result)

In this code, we define a list called my_list and a number called my_number.

We then use list comprehension to iterate over each element in my_list.

add my_number to each element, and create a new list from the results.

Finally, we print the contents of the result list

Output

[3, 4, 5, 6, 7]

Solution 3. Access Specific Items in the List

You need to access specific items in the list and perform the operation on each item individually.

Here’s an example of how to fix the error by accessing specific items in the list:

my_list = [1, 2, 3, 4, 5]
my_number = 2
result = []

for i in range(len(my_list)):
    result.append(my_list[i] + my_number)

print(result)

In this code, we define a list called my_list and a number called my_number.

We also create an empty list called result.

Next, we use a for loop to iterate over the indices of my_list.

On each iteration, we access the element of my_list at the current index and add my_number to it.

We then append the result to the result list.

Finally, we print the contents of the result list.

And those are the three possible solutions that you can use to fix “Typeerror unsupported operand type s for int and list”

I hope one or more of them helps you to fix the error.

Here are the other fixed Python errors that you can visit, you might encounter them in the future.

  • Attributeerror module tensorflow compat v1 has no attribute contrib
  • Attributeerror: module ‘collections’ has no attribute ‘iterable’ 
  • Attributeerror module has no attribute

Conclusion

In conclusion, The “Typeerror unsupported operand type s for int and list” occurs when you use the operators to integers and lists. To resolve this error, various solutions are used in Python, such as using for Loop, using List Comprehension, and accessing specific items in the list.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

We’re happy to help you.

Happy coding! Have a Good day and God bless.

Have you ever encountered a TypeError in your Python code that reads «Unsupported Operand Type(s) for +: ‘int’ and ‘List'»? This error message can be pretty confusing, but don’t worry! In this guide, we’ll explain what this error means and provide you with a step-by-step solution to fix it.

What is the TypeError: Unsupported Operand Type(s) for +: ‘int’ and ‘List’ Error?

This TypeError occurs when you try to add an integer and a list together using the + operator. In Python, you can only add objects that are of the same type. When you try to add an integer and a list, Python doesn’t know how to combine them, and it raises the TypeError we’re discussing.

How to Fix the TypeError: Unsupported Operand Type(s) for +: ‘int’ and ‘List’ Error

To fix this error, you need to make sure that you’re adding objects of the same type. Here are the steps to follow:

  1. Check the code that’s causing the error. Look for any instances where you’re adding an integer and a list together using the + operator.
  2. Determine which object you want to keep. Do you want to keep the integer or the list?
  3. Convert the other object to match the type of the one you’re keeping. If you’re keeping the integer, convert the list to an integer. If you’re keeping the list, convert the integer to a list.
  4. Add the two objects together using the + operator.

Here’s an example of how to fix this error when you want to keep the list:

my_list = [1, 2, 3, 4, 5]
my_int = 10

# This line causes the TypeError
new_list = my_int + my_list

# Convert the integer to a list
my_int = [my_int]

# Add the two objects together
new_list = my_int + my_list

# The result is [10, 1, 2, 3, 4, 5]

FAQs

Q1. Can this error occur with other types of objects?

Yes, this error can occur when you try to add objects of different types together using the + operator. For example, it can occur when you try to add a string and a list together.

Q2. Can I use a different operator to combine objects of different types?

Yes, you can use different operators to combine objects of different types. For example, you can use the extend() method to add items from one list to another.

Q3. Why does Python raise this error?

Python raises this error to prevent you from accidentally combining objects of different types. Combining objects of different types can lead to unexpected results or errors in your code.

Q4. How can I avoid this error?

You can avoid this error by making sure that you’re only combining objects of the same type. If you need to combine objects of different types, you should convert them to the same type before adding them together.

Q5. Can I add two lists together using the + operator?

Yes, you can add two lists together using the + operator. When you add two lists together, Python concatenates them into a single list.

  • Python TypeError: unsupported operand type(s) for +: ‘int’ and ‘list’ — Stack Overflow
  • Python Lists — W3Schools

  • #1

Python:

import pygame

pygame.init()

display_w = 800 
display_h = 600 

display = pygame.display.set_mode((display_w, display_h)) 

pers_width = 60
pers_height = 100

def rect(offset, height):
    pers_0_x = display_w // offset
    pers_0_y = display_h - height - pers_height
    pers_1_x = display_w // offset
    pers_1_y = display_h - height + pers_height
rect(4, [100, 600])

def rect(offset, height):
    pers_2_x = display_w - offset
    pers_2_y = display_h - height - pers_height
    pers_3_x = display_w - offset
    pers_3_y = display_h - height + pers_height
rect(260, [100, 600])

def rungame():
    game = True
    while game: 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                pygame.quit() 
                quit()
display.fill((255, 255, 255))
pygame.draw.rect(display, (251,186,0), (pers_0_x, pers_0_y, pers_width, pers_height)) 
pygame.draw.rect(display, (168,91,56), (pers_1_x, pers_1_y, pers_width, pers_height))
pygame.draw.rect(display, (34,253,48), (pers_2_x, pers_2_y, pers_width, pers_height)) 
pygame.draw.rect(display, (11,28,189), (pers_3_x, pers_3_y, pers_width, pers_height)) 
pygame.display.update() 
rungame()

Код:

Traceback (most recent call last):
  File "D:PythonGame on PythonПерсонаж1.py", line 21, in <module>
    rect(4, [100, 600])
  File "D:PythonGame on PythonПерсонаж1.py", line 18, in rect
    pers_0_y = display_h - height - pers_height
TypeError: unsupported operand type(s) for -: 'int' and 'list'

Как исправить подобную ошибку на примере вот этого кода? Если знаете, помогите пожалуйста.


0

abc


  • #2

Переведите ошибку и посмотрите, что вы передаёте в качестве height


0

overpathz


  • #3

В 18 (и не только) строке, ты передаешь list. В самом методе, над аргументом height выполняются операции сложения и вычитания. (То есть ты складываешь число и список)
В общем, при вызове метода rect(), передай аргумент нужного типа.
И потом, если решить эту проблему, у тебя появятся другие — ты используешь локальные переменные метода за его пределами.
Можешь вернуть лист значений, и по индексу что-то отковырять, либо, не использовать локальные переменные.

upd: Ко всему вышеперечисленному, у тебя 2 одинаковых метода.

Бырое решение, чисто чтобы оно запустилось:

Python:

import pygame

pygame.init()

display_w = 800
display_h = 600

display = pygame.display.set_mode((display_w, display_h))

pers_width = 60
pers_height = 100


def rect(offset, height):
    pers_0_x = display_w // offset
    pers_0_y = display_h - height - pers_height
    pers_1_x = display_w // offset
    pers_1_y = display_h - height + pers_height
    return [pers_0_x, pers_0_y, pers_1_x, pers_1_y]


rect(4, 600)


def rect(offset, height):
    pers_2_x = display_w - offset
    pers_2_y = display_h - height - pers_height
    pers_3_x = display_w - offset
    pers_3_y = display_h - height + pers_height
    return [pers_2_x, pers_2_y, pers_3_x, pers_3_y]


rect(260, 600)


def rungame():
    game = True
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


display.fill((255, 255, 255))

pygame.draw.rect(display, (251,186,0), (rect(260, 600)[0], rect(260, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (168,91,56), (rect(260, 600)[2], rect(260, 600)[3], pers_width, pers_height))
pygame.draw.rect(display, (34,253,48), (rect(260, 600)[0], rect(260, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (11,28,189), (rect(260, 600)[2], rect(260, 600)[3], pers_width, pers_height))
pygame.display.update()
rungame()

Последнее редактирование: Май 28, 2021


0

  • #4

В 18 (и не только) строке, ты передаешь list. В самом методе, над аргументом height выполняются операции сложения и вычитания. (То есть ты складываешь число и список)
В общем, при вызове метода rect(), передай аргумент нужного типа.
И потом, если решить эту проблему, у тебя появятся другие — ты используешь локальные переменные метода за его пределами.
Можешь вернуть лист значений, и по индексу что-то отковырять, либо, не использовать локальные переменные.

upd: Ко всему вышеперечисленному, у тебя 2 одинаковых метода.

Бырое решение, чисто чтобы оно запустилось:

Python:

import pygame

pygame.init()

display_w = 800
display_h = 600

display = pygame.display.set_mode((display_w, display_h))

pers_width = 60
pers_height = 100


def rect(offset, height):
    pers_0_x = display_w // offset
    pers_0_y = display_h - height - pers_height
    pers_1_x = display_w // offset
    pers_1_y = display_h - height + pers_height
    return [pers_0_x, pers_0_y, pers_1_x, pers_1_y]


rect(4, 600)


def rect(offset, height):
    pers_2_x = display_w - offset
    pers_2_y = display_h - height - pers_height
    pers_3_x = display_w - offset
    pers_3_y = display_h - height + pers_height
    return [pers_2_x, pers_2_y, pers_3_x, pers_3_y]


rect(260, 600)


def rungame():
    game = True
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


display.fill((255, 255, 255))

pygame.draw.rect(display, (251,186,0), (rect(260, 600)[0], rect(260, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (168,91,56), (rect(260, 600)[2], rect(260, 600)[3], pers_width, pers_height))
pygame.draw.rect(display, (34,253,48), (rect(260, 600)[0], rect(260, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (11,28,189), (rect(260, 600)[2], rect(260, 600)[3], pers_width, pers_height))
pygame.display.update()
rungame()

Но можно поинтересоваться, почему выводится только 1 прямоугольник?


0

overpathz


  • #5

Но можно поинтересоваться, почему выводится только 1 прямоугольник?

Потому что мы в параметры передаем одни и те же значения. Вот, другие значения.

Python:

import pygame

pygame.init()

display_w = 800
display_h = 600

display = pygame.display.set_mode((display_w, display_h))

pers_width = 60
pers_height = 100


def rect(offset, height):
    pers_0_x = display_w // offset
    pers_0_y = display_h - height - pers_height
    pers_1_x = display_w // offset
    pers_1_y = display_h - height + pers_height
    return [pers_0_x, pers_0_y, pers_1_x, pers_1_y]


rect(4, 600)


def rect(offset, height):
    pers_2_x = display_w - offset
    pers_2_y = display_h - height - pers_height
    pers_3_x = display_w - offset
    pers_3_y = display_h - height + pers_height
    return [pers_2_x, pers_2_y, pers_3_x, pers_3_y]


rect(260, 600)


def rungame():
    game = True
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


display.fill((255, 255, 255))

pygame.draw.rect(display, (251,186,0), (rect(260, 600)[0], rect(260, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (168,91,56), (rect(260, 600)[2], rect(260, 600)[3], pers_width, pers_height))

pygame.draw.rect(display, (34,253,48), (rect(100, 600)[0], rect(100, 600)[1], pers_width, pers_height))
pygame.draw.rect(display, (11,28,189), (rect(100, 600)[2], rect(100, 600)[3], pers_width, pers_height))
pygame.display.update()
rungame()

1622303719998.png


0

overpathz


  • #6

Сам не понял что сделал, но кода стало меньше. (завернул повторяющие фрагменты в функцию)

Python:

import pygame

pygame.init()

display_w = 800
display_h = 600

display = pygame.display.set_mode((display_w, display_h))

pers_width = 60
pers_height = 100


def rect(offset, height):
    pers_0_x = display_w // offset
    pers_0_y = display_h - height - pers_height
    pers_1_x = display_w // offset
    pers_1_y = display_h - height + pers_height
    return [pers_0_x, pers_0_y, pers_1_x, pers_1_y]


def draw(color, offset, height):
    pygame.draw.rect(display, color, (rect(offset, height)[2], rect(offset, height)[3], pers_width, pers_height))


def run_game():
    game = True
    while game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


display.fill((255, 255, 255))


draw('red', 300, 600)
draw('black', 5, 600)


pygame.display.update()
run_game()

Понравилась статья? Поделить с друзьями:
  • Unrecognized upnp response ошибка upnp wizard
  • Unrecognized command line option ошибка
  • Unreal engine ошибка при запуске игры
  • Unreal engine ошибка ls 0019
  • Unreal engine код ошибки e10 0