AttributeError: 'list' object has no attribute 'join'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Ivana Cajina

AttributeError: 'list' object has no attribute 'join' #

The Python "AttributeError: 'list' object has no attribute 'join'" occurs when we call the join() method on a list object. To solve the error, call the join method on the string separator and pass the list as an argument to join, e.g. '-'.join(['a','b']).

attributeerror list object has no attribute join

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] # ⛔️ AttributeError: 'list' object has no attribute 'join' my_str = my_list.join('-')

We tried to call the join() method on the list which caused the error.

To solve the error, call the join() method on the string separator and pass it the list as an argument.

main.py
my_list = ['a', 'b', 'c'] my_str = '-'.join(my_list) print(my_str) # 👉️ "a-b-c"

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between elements.

If you don't need a separator and just want to join the list elements into a string, call the join() method on an empty string.

main.py
my_list = ['a', 'b', 'c'] my_str = ''.join(my_list) print(my_str) # 👉️ "abc"

Note that the join() method raises a TypeError if there are any non-string values in the iterable.

If your list contains numbers, or other types, convert all of the values to string before calling join().

main.py
my_list = ['a', 'b', 1, 2] all_strings = list(map(str, my_list)) print(all_strings) # 👉️ ['a', 'b', '1', '2'] result = ''.join(all_strings) print(result) # 👉️ "ab12"
The "AttributeError: 'list' object has no attribute 'join'" occurs when we try to call the join() method on a list instead of a string.

To solve the error, you have to call the method on a string, and pass the list as an argument to join().

You can view all the attributes an object has by using the dir() function.

main.py
my_list = ['a', 'b', 'c'] # 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index', # 'insert', 'pop', 'remove', 'reverse', 'sort' ...] print(dir(my_list))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: list object has no attribute" error.

Since join() is not a method implemented by lists, the error is caused.

Use the search field on my Home Page to filter through my more than 1,000 articles.