About "can only concatenate str (not “list”) to str" in Python
Tags: python, programming
Published: 2023-02-04 12:49:59

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-list-to-str-fix) for a 💯 user experience. _~reza_

The Python error “TypeError: can only concatenate str (not “list”) to str” occurs if you concatenate a string with a list. 

Here’s what the error looks like on Python 3.

```
File "/dwd/sandbox/test.py", line 3, in 
    print('Resources: ' + books)
          ~~~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "list") to str
```

On Python 2.7, the error is slightly different, though: 

```
Traceback (most recent call last):
  File "test.py", line 3, in 
    print('Resources: ' + books)
TypeError: cannot concatenate 'str' and 'list' objects
```

But it occurs for the same reason.

## Why does it happen?

As you probably know, programming languages are either strongly typed or loosely typed.

[Strongly-typed programming languages](https://www.decodingweb.dev/how-to-learn-a-programming-language#type-systems) such as Python have a strict type system to help the programmer avoid data-type-related mistakes - meaning some operations aren't allowed on some data types. For instance, you can't divide `20` by `'4'` (because `'4'` is a string value) - depending on the operation, the error messages might vary.

Whenever you declare a variable like `name = 'John'`, as a dynamically-typed language, Python determines the data type to be a string. 

Now, if you try to concatenate it with a list, you'll get the "TypeError: can only concatenate str (not "list") to str" error.

## How to fix TypeError: can only concatenate str (not "list") to str

Fixing type errors such as this one is easy. If you need to use the + operator, check if the operands on either side have the same type. Remember: birds of a feather flock together 🦜 `+` 🦜

But if you want to insert the values into a string, there are multiple ways of doing it:

1. <u>Convert the list into a string value with the str.join() method</u>
2. <u>Access list items individually</u>
3. <u>Use print() with multiple arguments - ideal for debugging</u>
4. <u>Use an f-string</u>
5. <u>Use printf-style formatting</u>

Let's explore each method.

**Convert the list into a string with the `str.join()` method:** If you want to concatenate the items of a list to a string value, use `str.join()` like so:

```python
books = ['Fluent Python', 'Head First Python']
output = 'Resources: ' + ', '.join(books)

print(output)
# output: Resources: Fluent Python, Head First Python
```

In the above code, we separate the list items by a comma. Please note we call the join method on the separator string (in this case: `', '`). It seems weird, but that's how it works!

**Access list items individually:** Sometimes, you need to concatenate a single list item with a string value, but you use the whole list object by mistake.

In that case, you need to access the item by its index:

```python
books = ['Fluent Python', 'Head First Python']
output = 'Top Pick: ' + books[1]

print(output)
# output: Top Pick: Head First Python
```

**Use `print()` with multiple arguments - ideal for debugging:** If you're concatenating a string with a list and readability isn't a concern, you can pass the string and the list as separate arguments to the `print()` function.

All the positional arguments passed to the `print()` function are automatically converted to strings - like how `str()` works.

```python
books = ['Fluent Python', 'Head First Python']

print('Fetched these books:', books)
# output: Fetched these books: ['Fluent Python', 'Head First Python']
```

As you can see, the `print()` function outputs the arguments separated by a space. You can also change the separator via the sep keyword argument.

**Use an f-string:** Formatted string literals (a.k.a f-strings) are a robust way of formatting strings because they allow you to use Python expressions directly in string values (in a pair of curly brackets `{}`). 

You create an f-string by prefixing it with `f` or `F` and writing expressions inside curly braces:

```python
books = ['Fluent Python', 'Head First Python']

print(f'Fetched these books: {books}')
# output: Fetched these books: ['Fluent Python', 'Head First Python']
```

Additionally, you can join the list items before using it in the string:

```python
books = ['Fluent Python', 'Head First Python']
book_list = ', '.join(books)

print(f'Fetched these books: {book_list}')
# output: Fetched these books: Fluent Python, Head First Python
```

**Use printf-style formatting:** In the old string formatting (a.k.a printf-style string formatting), we use the `%` (modulo) operator to generate dynamic strings (string `%` values).

The string operand is a string literal containing one or more placeholders identified with `%`, while the values operand can be a single value or a tuple of values.

```python
books = ['Fluent Python', 'Head First Python']

print('Fetched these books: %s' % books)
# output: Fetched these books: ['Fluent Python', 'Head First Python']
```

When using the old-style formatting, check if your format string is valid. Otherwise, you'll get another type error: [not all arguments converted during string formatting](https://www.decodingweb.dev/python-typeerror-not-all-arguments-converted-during-string-formatting-fix).

Alright, I think that does it! I hope this quick guide helped you fix your problem.

Thanks for reading!

**❤️ You might like:**

- [Not all arguments converted during string formatting error in Python (Fixed)](https://www.decodingweb.dev/python-typeerror-not-all-arguments-converted-during-string-formatting-fix)
- [TabError: inconsistent use of tabs and spaces in indentation (Python)](https://www.decodingweb.dev/python-taberror-inconsistent-use-of-tabs-and-spaces-in-indentation-fix)
- [How to fix the "TypeError: unhashable type: 'dict'" error in Python](https://www.decodingweb.dev/python-typeerror-unhashable-type-dict-fixed)
- [How to reverse a range in Python (with examples)](https://www.decodingweb.dev/reverse-a-range-in-python)
- [TypeError: missing 1 required positional argument: 'self' (Fixed)](https://www.decodingweb.dev/python-typeerror-missing-1-required-positional-argument-self)
- [Unindent does not match any outer indentation level error in Python (Fixed)](https://www.decodingweb.dev/python-indentationerror-unindent-does-not-match-any-outer-indentation-level-fix)