How To Solve The TypeError: Can Only Concatenate List (Not “Str”) To List

TypeError: can only concatenate list (not “str”) to list

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

How to solve the 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:

Leave a Reply

Your email address will not be published. Required fields are marked *