Are you finding a way to solve the TypeError: can only concatenate list (not “str”) to list? Let’s follow this article. We will help you to fix it.
The cause of this error
The main reason for the “TypeError: can only concatenate list (not str) to list” is that you’re trying to concatenate a list with a string. Logically, two objects with different data types can not be concatenated.
Example:
myList = ["Learn","Share"]
def addElementToList(value):
newList = myList+str(value) # Here is the cause of this error
print(newList)
addElementToList("IT")
Output
The error will show if you try to run this code.
TypeError: can only concatenate list (not "str") to list
We’ve tested effectively with 2 solutions to solve this error by using the join() method and using the append() method. Reading to the end of the article to see how we solve this problem.
Using the join() method
To avoid this error, you can use the join() method to convert a list to a string. Then add two strings.
Syntax:
string.join(iterable)
Parameter:
- iterable: any iterable object where all the returned values are strings.
Return value: the return value is a string specified as the separator.
Example:
myList = ["Learn","Share"]
# Use join() method to conver myList to string
myList = ''.join(myList)
def addElementToList(value):
# Add two strings
newList = myList+str(value)
print("After converting myList into a string:",newList)
addElementToList("IT")
Output
After converting myList into a string: LearnShareIT
Using the append() method
The other simple way to solve the error is using the append() method to add a string to the list.
Syntax:
list.append(element)
Parameter:
- element: an element of any type (string, number, etc.)
Return value: the return value is a list. Adding the value at the end of the list.
Example:
myList = ["Learn","Share"]
def addElementToList(value):
# Use append method to add value into myList
myList.append(value)
print(myList)
addElementToList("IT")
Output
['Learn', 'Share', 'IT']
Summary
In this article, we already explained to you how to solve the TypeError: can only concatenate list (not “str”) to list with two solutions. We always hope this information will be of some help to you. If you have any questions, don’t hesitate and leave your comment below. I will answer as possible. Thank you for your read!
Maybe you are interested:
- NameError: name ‘pd’ is not defined in Python
- TypeError: ‘bool’ object is not callable in Python
- TypeError: ‘tuple’ object does not support item assignment
My name is Fred Hall. My hobby is studying programming languages, which I would like to share with you. Please do not hesitate to contact me if you are having problems learning the computer languages Java, JavaScript, C, C#, Perl, or Python. I will respond to all of your inquiries.
Name of the university: HUSC
Major: IT
Programming Languages: Java, JavaScript, C , C#, Perl, Python
Что означает ошибка TypeError: can only concatenate str (not «int») to str
Это значит, что вы пытаетесь сложить строки с числами
Это значит, что вы пытаетесь сложить строки с числами
Программист освоил JavaScript и начал изучать Python. Чтобы освоиться в языке, он переносит проекты с одного языка на другой — убирает точки с запятой, добавляет отступы и меняет команды одного языка на такие же команды из другого языка.
Один из фрагментов его кода после перевода в Python выглядит так:
# зарплата в месяц
month = 14200
# плата за ЖКХ
regular_cost = 5800
# функция, которая считает и возвращает долю ЖКХ в бюджете
def calculate(budget,base):
message = 'На коммунальные платежи уходит ' + base + 'р. - это ' + base/budget*100 + ' процентов от ежемесячного бюджета'
return message
# отправляем в функцию переменные и выводим результат на экран
print(calculate(month,regular_cost))
Но после запуска программист получает ошибку:
❌ TypeError: can only concatenate str (not «int») to str
Странно, но в JavaScript всё работало, почему же здесь код сломался?
Что это значит: компилятор не смог соединить строки и числа, поэтому выдал ошибку.
Когда встречается: в языках со строгой типизацией, например в Python, когда у всех переменных в выражении должен быть один и тот же тип данных. А вот в JavaScript, который изучал программист до этого, типизация нестрогая, и компилятор сам мог привести все части выражения к одному типу.
Что делать с ошибкой TypeError: can only concatenate str (not «int») to str
Раз это проблема строгой типизации, то для исправления этой ошибки нужно просто привести все части к одному типу.
В нашем случае мы хотим получить на выходе строку, поэтому все слагаемые должны быть строкового типа. Но base и base/budget*100 — это числа, поэтому просто так их сложить со строками не получится. Чтобы выйти из ситуации, явно преобразуем их в строки командой str():
message = 'На коммунальные платежи уходит ' + str(base) + 'р. - это ' + str(base/budget*100) + ' процентов от ежемесячного бюджета'
Команда str() делает так, что всё внутри неё приводится к строке и она отдаёт дальше строку. В итоге операция склейки строк проходит как ожидаемо: строка к строке даёт строку. Нет повода для беспокойства.
Вёрстка:
Кирилл Климентьев
Получите ИТ-профессию
В «Яндекс Практикуме» можно стать разработчиком, тестировщиком, аналитиком и менеджером цифровых продуктов. Первая часть обучения всегда бесплатная, чтобы попробовать и найти то, что вам по душе. Дальше — программы трудоустройства.
Начать карьеру в ИТ

Если вы хотите их в виде списка, вы должны изменить:
result = result + c
в:
result.append (c)
Однако имейте в виду, что ваш код не совсем соответствует вашим спецификациям.
В частности, ваша функция strip_digits Не удаляя (то есть выбрасывая) цифры, он фактически составляет их список, поэтому я бы переименовал его в get_digits. я бы тоже поменял numberless_str в number_str так как он вовсе не бесчисленный.
Во-вторых, становится все символы из входной строки, а не только цифры.
В-третьих, он действует на исходную строку, а не на обратную.
Наконец, вы должны возвращение что собой представляет result из вашей функции, иначе вы ничего не получите (None).
Код лучше было бы написать так:
def reverse_str(string):
revstring = ''
length=len (string)
i = length - 1
while i >= 0:
revstring = revstring + string[i]
i = i - 1
return revstring
def get_digits(string):
result = [] # <- start with empty list.
for c in string: # <- check every char
if c in "1234567890": # <- but only transfer digits
result.append (c) # <- use append for lists
return result
string = raw_input("Enter a string->")
new_str = reverse_str(string)
print new_str
number_str = get_digits(new_str)
print number_str
4kpt_V
вот тут описано почему так происходит
Там описано другое
Operator Overload, __and__, (+) and __iand__ (+=)
Both + and += operators are defined for list. They are semantically similar to extend.
my_list + another_list creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.
my_list += another_list modifies the list in-place (it is the in-place operator, and lists are mutable objects, as we’ve seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.
То есть он пишет только про списки. А то, что он пишет, что оно может быть любым итераблом в случае +=, ну, так он описал просто поведение этого бага. Это же не документация, иначе должно быть логическое обоснование, почему + не работает так же, а в документации на этот счёт ничего нет.
На списках оно работает.
lst = lst + [1, 2] - работает
lst += [1, 2] - работает
А на строках (кортежах и других итерабельных типах) не работает.
lst = lst + 'abc' - не работает
lst += 'abc' - работает
Либо операция + должна и со строками работать, либо операция += не должна со строками работать.
Это ошибка ядра питона. И, судя по поведению bytearray(), оно не должно работать со строками, потому что list() и bytarray() считаются подобными мутабельными типами.
Вот ещё итерабельный тип.
>>> lst = [1, 2, 3] >>> >>> lst + range(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "range") to list >>> >>> lst += range(3) >>> >>> lst [1, 2, 3, 0, 1, 2] >>>
Если он пишет, что не может сконкатенировать их, то и в составном присваивании, где также используется конкатенация, он не должен мочь этого. Если же он может так конкатенировать, то должен мочь везде. И bytearray() должен иметь такое же поведение, потому что эти типы устроены одинаково.
Отредактировано py.user.next (Март 25, 2017 00:47:31)
Hi, i’m trying to mirror the channel box attributes of my left joint chain from left to right.
However i’m getting an error with list concatenation!!
Image and code attached below
Can someone help me please?
Thanks
Daniel
______________________________
import maya.cmds as cmds
sel = cmd.ls(sl=True, dag=True)
leftSel = sel[:len(sel)/2]
rightSel = sel[len(sel)/2:]
cbAttr = cmd.listAttr(leftSel, k=1)
for i in cbAttr:
L_objVal = cmds.getAttr(leftSel + ‘.’ + i)
if i == ‘translateX’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal*-1)
if i == ‘translateY’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘translateZ’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘rotateX’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘rotateY’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘rotateZ’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘scaleX’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘scaleY’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)
if i == ‘scaleZ’:
cmds.setAttr(rightSel + ‘.’ + i, L_objVal)





