Can Only Concatenate List (Not Int) to List in Python
We will introduce in this article how to resolve the error message "can only concatenate list (not int) to list"
in Python with the help of an example.
the TypeError: can only concatenate list (not "int")
in Python
In Python, lists are a fundamental type of data structure and built-in data structures used to store a collection of items. They are used extensively in programming in various fields, such as data analytics, web development, machine learning, text processing, and many more.
While working with lists, there are some situations in which we want to concatenate an int, string, or float data type with a list. In Python, we cannot concatenate a list to any other data type without converting them to a list.
When we try to concatenate an int data type to a list, we get the error message "can only concatenate list (not int) to list"
.
Let’s go through an example in which we will recreate this error message by trying to concatenate an int to a list, as shown below.
Code Example:
# Python
students = [145]
new_addmissions = 45
all_students = students + new_addmissions
Output:
As demonstrated by the example above, an error message was returned when we tried to concatenate an int with a list. In Python, resolving this error message by just converting the int to a list is easy, as shown below.
Code Example:
# Python
students = [145]
new_addmissions = 45
add_student = [new_addmissions]
all_students = students + add_student
print(all_students)
Output:
Following this easy solution, we can also concatenate other data types, such as string and floating point, as shown below.
# Python
students = ["Husnain", "Susan"]
new_addmissions = "Alex"
add_student = [new_addmissions]
all_students = students + add_student
print(all_students)
Output:
I hope this article has helped you learn something new and solved your issue. We can easily concatenate the other data types with a list by just converting them to a list.
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedInRelated Article - Python Error
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python