AttributeError: 'list' object has no attribute 'X' in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
23 min

banner

# Table of Contents

  1. AttributeError: 'list' object has no attribute 'X' in Python
  2. AttributeError: 'list' object has no attribute 'ITEMS'
  3. AttributeError: 'list' object has no attribute 'LEN'
  4. AttributeError: 'list' object has no attribute 'LOWER'
  5. AttributeError: 'list' object has no attribute 'STRIP'
  6. AttributeError: 'list' object has no attribute 'VALUES' or 'KEYS'
  7. AttributeError: 'list' object has no attribute 'ENCODE'
  8. AttributeError: 'list' object has no attribute 'GET'
  9. AttributeError: 'list' object has no attribute 'STARTSWITH'
  10. AttributeError: 'list' object has no attribute 'JOIN'

# AttributeError: 'list' object has no attribute 'X' in Python

The Python "AttributeError: 'list' object has no attribute" occurs when we access an attribute that doesn't exist on a list.

To solve the error, access the list element at a specific index or correct the assignment.

attributeerror list object has no attribute

Here is an example of how the error occurs.

main.py
my_list = ['bobby_hadz', 'dot_com'] # ๐Ÿ‘ˆ๏ธ list # โ›”๏ธ AttributeError: 'list' object has no attribute 'split' result = my_list.split('_')

We created a list with 2 elements and tried to call the split() method on the list which caused the error.

# Access the list at a specific index before accessing an attribute

To solve the error in this situation, we have to access the list at a specific index because split is a method on strings.

main.py
my_list = ['bobby_hadz', 'dot_com'] # ๐Ÿ‘ˆ๏ธ list result = my_list[0].split('_') print(result) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz']

access list at index before accessing attribute

We accessed the list at index 0 to call the split() method on the first list element.

# Calling a method on each element in a list

If you are trying to call a method on each element in a list, use a for loop to iterate over the list.

main.py
my_list = ['bobby', 'hadz', 'com'] new_list = [] for word in my_list: new_list.append(word.upper()) result = word.upper() # BOBBY # HADZ # COM print(result) print(new_list) # ๐Ÿ‘‰๏ธ ['BOBBY', 'HADZ', 'COM']

call method on each element in list

We used a for loop to iterate over the list and called the upper() method to uppercase each string.

You can also use a list comprehension if you need to call a function on each element in a list.

main.py
my_list = ['bobby', 'hadz'] new_list = [item.upper() for item in my_list] print(new_list) # ๐Ÿ‘‰๏ธ ['BOBBY', 'HADZ']
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

# Joining a list into a string with a separator

If you meant to join a list into a string with a separator, call the join() method on the string separator instead.

main.py
my_list = '_'.join(['bobby', 'hadz', 'com']) print(my_list) # ๐Ÿ‘‰๏ธ 'bobby_hadz_com' without_separator = ''.join(['bobby', 'hadz', 'com']) print(without_separator) # ๐Ÿ‘‰๏ธ 'bobbyhadzcom' mixed_list = [0, 'bobby', 1, 'hadz'] a_str = ','.join(str(element) for element in mixed_list) print(a_str) # ๐Ÿ‘‰๏ธ 0,bobby,1,hadz

join list into string with separator

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

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

# Checking if a list contains an element

A common source of the error is trying to use a list.find() method.

main.py
my_list = ['apple', 'banana', 'kiwi'] # โ›”๏ธ AttributeError: 'list' object has no attribute 'find' print(my_list.find('banana'))

We created a list of 3 elements and tried to call the find() method on it which caused the error because find() is a string method.

If you need to check if a value is in a list, use the in operator.

main.py
my_list = ['apple', 'banana', 'kiwi'] if 'banana' in my_list: print('banana is in the list') # ๐Ÿ‘‰๏ธ this runs else: print('banana is not in the list')

The in operator returns True if the value is in the list and false otherwise.

# Get the index of a value in a list

If you need to get the index of a value in a list, use the index() method.

main.py
my_list = ['apple', 'banana', 'kiwi'] result = my_list.index('banana') print(result) # ๐Ÿ‘‰๏ธ 1

The list.index() method returns the index of the first item whose value is equal to the provided argument.

# Adding elements to a list

If you need to add a single element to a list, use the list.append() method.

main.py
a_list = ['bobby', 'hadz'] a_list.append('com') print(a_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

If you need to add multiple elements to a list, use the list.extend() method.

main.py
a_list = ['bobby'] a_list.extend(['hadz', 'com']) print(a_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

# Check if an object contains an attribute

If you need to check whether an object contains an attribute, use the hasattr() function.

main.py
example = ['bobby', 'hadz', 'com'] if hasattr(example, 'my_attribute'): print(example.my_attribute) else: print('Attribute is not present on object') # ๐Ÿ‘‰๏ธ This runs

The hasattr function takes the following 2 parameters:

NameDescription
objectThe object we want to test for the existence of the attribute
nameThe name of the attribute to check for in the object

The hasattr() function returns True if the string is the name of one of the object's attributes, otherwise, False is returned.

Using the hasattr function would handle the error if the attribute doesn't exist on the object, however, you still have to figure out where the variable gets assigned a list value in your code.

# Track down where the variable got assigned a list and correct the assignment

If you created a list by mistake, track down where the variable gets assigned a list and correct the assignment.

The error occurs when we access an attribute that doesn't exist on the list data type.

# Using a dictionary instead of a list

If you meant to use a dictionary, wrap key-value pairs in curly braces.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} print(my_dict['name']) # ๐Ÿ‘‰๏ธ "Bobby Hadz" print(my_dict['age']) # ๐Ÿ‘‰๏ธ 30

A dictionary is used to store key-value pairs.

# Creating a class and accessing attributes

If you meant to create a class and access its attributes, declare a class and instantiate it.

main.py
class Employee(): def __init__(self, name, age): self.name = name self.age = age # ๐Ÿ‘‡๏ธ Create an instance emp = Employee('Bobby Hadz', 30) # ๐Ÿ‘‡๏ธ Access its attributes print(emp.name) # ๐Ÿ‘‰๏ธ "Bobby hadz" print(emp.age) # ๐Ÿ‘‰๏ธ 30

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

main.py
my_list = ['bobby', 'hadz', 'com'] # ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '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 class's attributes, and recursively of the attributes of its bases.

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

# Examples of solving the error for specific methods

Here are some examples of solving the error for specific methods. Click on the link to navigate to the subheading.

  1. AttributeError: 'list' object has no attribute 'items'
  2. AttributeError: 'list' object has no attribute 'len'
  3. AttributeError: 'list' object has no attribute 'lower'
  4. AttributeError: 'list' object has no attribute 'strip'
  5. AttributeError: 'list' object has no attribute 'values' or 'keys'
  6. AttributeError: 'list' object has no attribute 'encode'
  7. AttributeError: 'list' object has no attribute 'get'
  8. AttributeError: 'list' object has no attribute 'startswith'
  9. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'items'" occurs when we call the items() method on a list instead of a dictionary.

To solve the error, call items() on a dict, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute items

Here is an example of how the error occurs.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Alice'}, ] # โ›”๏ธ AttributeError: 'list' object has no attribute 'items' print(my_list.items())

We created a list with 3 dictionaries and tried to call the items() method on the list which caused the error because items() is a dictionary method.

One way to solve the error is to access a list element at a specific index.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Alice'}, ] result = list(my_list[0].items()) print(result) # ๐Ÿ‘‰๏ธ [('id', 1), ('name', 'Alice')]

We accessed the first element (dictionary) in the list and called the items() method.

If you need to call the items() method on all dictionaries in the list, use a for loop.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] for person in my_list: print(person.items())

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # ๐Ÿ‘‰๏ธ dict_items([('id', 1), ('name', 'Alice')])

A dictionary is a collection of key-value pairs wrapped in curly braces, whereas a list is a sequence of comma-separated items.

If you need to find a dictionary in a list, use a generator expression.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] result = next( (item for item in my_list if item['name'] == 'Bobby Hadz'), {} ) print(result) # ๐Ÿ‘‰๏ธ {'id': 2, 'name': 'Bobby Hadz'} print(result.get('name')) # ๐Ÿ‘‰๏ธ "Bobby Hadz" print(result.get('id')) # ๐Ÿ‘‰๏ธ 2 print(result.items()) # ๐Ÿ‘‰๏ธ dict_items([('id', 2), ('name', 'Bobby Hadz')])

The generator expression in the example looks for a dictionary with a name key that has a value of Bob and returns the dictionary.

We used an empty dictionary as a fallback, so if a dictionary in the list has a name key with a value of Bob, the generator expression would return an empty dictionary.

If you need to find all dictionaries in the list that match a condition, use the filter() function.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Alice'}, ] new_list = list( filter(lambda person: person.get('name') == 'Alice', my_list) ) # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'Alice'}, {'id': 3, 'name': 'Alice'}] print(new_list)
The error occurs when we try to call the items() method on a list instead of a dictionary.

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

main.py
my_list = ['bobby', 'hadz', 'com'] # ๐Ÿ‘‰๏ธ [... '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 class's attributes, and recursively of the attributes of its bases.

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

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

  1. AttributeError: 'list' object has no attribute 'len'
  2. AttributeError: 'list' object has no attribute 'lower'
  3. AttributeError: 'list' object has no attribute 'strip'
  4. AttributeError: 'list' object has no attribute 'values' or 'keys'
  5. AttributeError: 'list' object has no attribute 'encode'
  6. AttributeError: 'list' object has no attribute 'get'
  7. AttributeError: 'list' object has no attribute 'startswith'
  8. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'len'" occurs when we access the len attribute on a list.

To solve the error, pass the list to the len function to get its length, e.g. len(['a', 'b']).

attributeerror list object has no attribute len

Here is an example of how the error occurs.

main.py
my_list = ['apple', 'banana', 'kiwi'] # โ›”๏ธ AttributeError: 'list' object has no attribute 'len' print(my_list.len())

The error was caused because list objects don't have a len attribute.

To get the list's length, pass it to the len() function.

main.py
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # ๐Ÿ‘‰๏ธ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If you need to get the length of an item in the list, access the list at the specific index.

main.py
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list[0]) print(result) # ๐Ÿ‘‰๏ธ 5

We accessed the list at index 0 and passed the result to the length function.

If you need to get the length of every element in the list, use a for loop.

main.py
my_list = ['apple', 'banana', 'kiwi'] for fruit in my_list: print(len(fruit))

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 class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you will get the error.

  1. AttributeError: 'list' object has no attribute 'lower'
  2. AttributeError: 'list' object has no attribute 'strip'
  3. AttributeError: 'list' object has no attribute 'values' or 'keys'
  4. AttributeError: 'list' object has no attribute 'encode'
  5. AttributeError: 'list' object has no attribute 'get'
  6. AttributeError: 'list' object has no attribute 'startswith'
  7. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'lower'" occurs when we call the lower() method on a list instead of a string.

To solve the error, call lower() on a string, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute lower

Here is an example of how the error occurs.

main.py
my_list = ['BOBBY', 'HADZ'] # โ›”๏ธ AttributeError: 'list' object has no attribute 'lower' my_list.lower()

We created a list with 2 elements and tried to call the lower() method on the list which caused the error.

The lower() method is string-specific, so we have to call it on a string, and not on a list object.

# Access the list at an index before calling lower()

One way to solve the error is to access the list at a specific index before calling lower().

main.py
my_list = ['BOBBY', 'HADZ'] result = my_list[0].lower() print(result) # ๐Ÿ‘‰๏ธ "bobby"

We accessed the list element at index 0 and called the lower() method on the string.

# Calling lower() on each element in the list

If you need to call the lower() method on each string in a list, use a list comprehension.

main.py
my_list = ['BOBBY', 'HADZ'] new_list = [word.lower() for word in my_list] print(new_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz']

If your list contains non-string values, use an if/else statement to only call lower() on the strings.

main.py
my_list = ['BOBBY', 0, 'HADZ', 1] new_list = [word.lower() if isinstance(word, str) else word for word in my_list] print(new_list) # ๐Ÿ‘‰๏ธ ['bobby', 0, 'hadz', 1]

Alternatively, you can use a for loop to call the lower() method on each string in the list.

main.py
my_list = ['BOBBY', 'HADZ', 'COM'] new_list = [] for word in my_list: new_list.append(word.lower()) result = word.lower() print(result) print(new_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

We used a for loop to iterate over the list and called the lower() method on each string.

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

The method doesn't change the original string, it returns a new string. Strings are immutable in Python.

# Track down where the variable got assigned a list

The error occurs when we try to call the lower() method on a list instead of a string.

To solve the error, you either have to correct the assignment of the variable and make sure to call lower() on a string, or call lower() on an element in the list that is of type string.

You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call lower() on each element.

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

main.py
my_list = ['bobby', 'hadz', 'com'] # ๐Ÿ‘‰๏ธ [... '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 class's attributes, and recursively of the attributes of its bases.

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

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

  1. AttributeError: 'list' object has no attribute 'strip'
  2. AttributeError: 'list' object has no attribute 'values' or 'keys'
  3. AttributeError: 'list' object has no attribute 'encode'
  4. AttributeError: 'list' object has no attribute 'get'
  5. AttributeError: 'list' object has no attribute 'startswith'
  6. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'strip'" occurs when we call the strip() method on a list instead of a string.

To solve the error, call strip() on a string, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute strip

Here is an example of how the error occurs.

main.py
my_list = [' hello ', ' world '] # โ›”๏ธ AttributeError: 'list' object has no attribute 'strip' my_list.strip()

We created a list with 2 elements and tried to call the strip() method on the list which caused the error.

The strip() method is string-specific, so we have to call it on a string, and not on a list object.

One way to solve the error is to access the list at a specific index before calling strip().

main.py
my_list = [' hello ', ' world '] result = my_list[0].strip() print(result) # ๐Ÿ‘‰๏ธ "hello"

We accessed the list element at index 0 and called the strip() method on the string.

If you need to call the strip() method on each string in a list, use a list comprehension.

main.py
my_list = [' hello ', ' world '] new_list = [word.strip() for word in my_list] print(new_list) # ๐Ÿ‘‰๏ธ ['hello', 'world']

Alternatively, you can use a for loop to call the strip() method on each string in the list.

main.py
my_list = [' hello ', ' world '] for word in my_list: result = word.strip() print(result) # ๐Ÿ‘‰๏ธ "hello", "world"

We used a for loop to iterate over the list and called the strip() method on each string.

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

The method does not change the original string, it returns a new string. Strings are immutable in Python.

The error occurs when we try to call the strip() method on a list instead of a string.

To solve the error, you either have to correct the assignment of the variable and make sure to call strip() on a string, or call strip() on an element in the list that is of type string.

You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call strip() on each element.

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 class's attributes, and recursively of the attributes of its bases.

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

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

  1. AttributeError: 'list' object has no attribute 'values' or 'keys'
  2. AttributeError: 'list' object has no attribute 'encode'
  3. AttributeError: 'list' object has no attribute 'get'
  4. AttributeError: 'list' object has no attribute 'startswith'
  5. AttributeError: 'list' object has no attribute 'join'

# AttributeError: 'list' object has no attribute 'values' or 'keys'

The Python "AttributeError: 'list' object has no attribute 'values'" occurs when we call the values() method on a list instead of a dictionary.

To solve the error, call values() on a dict, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute values

Here is an example of how the error occurs.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] # โ›”๏ธ AttributeError: 'list' object has no attribute 'values' print(my_list.values()) # โ›”๏ธ AttributeError: 'list' object has no attribute 'keys' print(my_list.keys())

attributeerror list object has no attribute keys

We created a list with 3 dictionaries and tried to call the values() and keys() methods on the list.

This caused the error because values() and keys() are dictionary methods.

# Access a list element at a specific index before calling the methods

One way to solve the error is to access a list element at a specific index.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] values = list(my_list[0].values()) print(values) # ๐Ÿ‘‰๏ธ [1, 'Alice'] keys = list(my_list[0].keys()) print(keys) # ๐Ÿ‘‰๏ธ ['id', 'name']

We accessed the list element at index 0 before calling the dict.values() and dict.keys() method.

If you need to call the values() method on all dictionaries in the list, use a for loop.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] for person in my_list: print(person.keys()) print(person.values())

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'Bobby Hadz'} print(my_dict.values()) # ๐Ÿ‘‰๏ธ dict_values([1, 'Alice']) print(my_dict.keys()) # ๐Ÿ‘‰๏ธ dict_values(['id', 'name'])

The dict.keys method returns a new view of the dictionary's keys.

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself.

# Finding a dictionary in a list before calling values() or keys()

If you need to find a dictionary in a list, use a generator expression.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Carl'}, ] result = next( (item for item in my_list if item['name'] == 'Bobby Hadz'), {} ) print(result) # ๐Ÿ‘‰๏ธ {'id': 2, 'name': 'Bobby Hadz'} print(result.get('name')) # ๐Ÿ‘‰๏ธ "Bobby Hadz" print(result.get('id')) # ๐Ÿ‘‰๏ธ 2 print(result.values()) # ๐Ÿ‘‰๏ธ dict_values([2, 'Bobby Hadz']) print(result.keys()) # ๐Ÿ‘‰๏ธ dict_keys(['id', 'name'])

The generator expression in the example looks for a dictionary with a name key that has a value of Bob and returns the dictionary.

We used an empty dictionary as a fallback, so if no dictionary in the list has a name key with a value of Bobby Hadz, the generator expression would return an empty dictionary.

# Finding all dictionaries in the list that meet a condition

If you need to find all dictionaries in the list that match a condition, use the filter() function.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby Hadz'}, {'id': 3, 'name': 'Alice'}, ] new_list = list( filter(lambda person: person.get('name') == 'Alice', my_list) ) # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'Alice'}, {'id': 3, 'name': 'Alice'}] print(new_list)

Similarly, the "AttributeError: 'list' object has no attribute 'keys'" error occurs when we try to call the keys() method on a list instead of a dictionary.

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

main.py
my_list = ['bobby', 'hadz', 'com'] # ๐Ÿ‘‰๏ธ [... '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 class's attributes, and recursively of the attributes of its bases.

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

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

  1. AttributeError: 'list' object has no attribute 'encode'
  2. AttributeError: 'list' object has no attribute 'get'
  3. AttributeError: 'list' object has no attribute 'startswith'
  4. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'encode'" occurs when we call the encode() method on a list instead of a string.

To solve the error, call encode() on a string, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute encode

Here is an example of how the error occurs.

main.py
my_list = ['bobby', 'hadz', 'com'] # โ›”๏ธ AttributeError: 'list' object has no attribute 'encode' my_list.encode('utf-8')

We created a list with 3 elements and tried to call the encode() method on the list which caused the error.

The encode() method is string-specific, so we have to call it on a string, and not on a list object.

One way to solve the error is to access the list at a specific index before calling encode().

main.py
my_list = ['bobby', 'hadz', 'com'] result = my_list[0].encode('utf-8') print(result) # ๐Ÿ‘‰๏ธ b'bobby'

We accessed the list element at index 0 and called the encode() method on the string.

If you need to call the encode() method on each string in a list, use a list comprehension.

main.py
my_list = ['bobby', 'hadz', 'com'] new_list = [word.encode('utf-8') for word in my_list] print(new_list) # ๐Ÿ‘‰๏ธ [b'bobby', b'hadz', b'com']

Alternatively, you can use a for loop to call the encode() method on each string in the list.

main.py
my_list = ['bobby', 'hadz', 'com'] for word in my_list: result = word.encode('utf-8') print(result)

We used a for loop to iterate over the list and called the encode() method on each string.

The str.encode() method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

The occurs when we try to call the encode() method on a list instead of a string.

To solve the error, you either have to correct the assignment of the variable and make sure to call encode() on a string, or call encode() on an element in the list that is of type string.

You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call encode() on each element.

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

main.py
my_list = ['bobby', 'hadz', 'com'] # ๐Ÿ‘‰๏ธ [... '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 class's 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 encode() is not a method implemented by lists, the error is caused.

  1. AttributeError: 'list' object has no attribute 'get'
  2. AttributeError: 'list' object has no attribute 'startswith'
  3. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'get'" occurs when we call the get() method on a list instead of a dictionary.

To solve the error, call get() on a dict, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror-list-object-has-no-attribute-get

Here is an example of how the error occurs.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] # โ›”๏ธ AttributeError: 'list' object has no attribute 'get' my_list.get('name')

We created a list with 3 dictionaries and tried to call the get() method on the list which caused the error because get() is a dictionary method.

One way to solve the error is to access a list element at a specific index.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] result = my_list[0].get('name') print(result) # ๐Ÿ‘‰๏ธ "Alice"

We accessed the list element at index 0 and used the get() method to get the value of the name key.

If you need to find a dictionary in a list, use a generator expression.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] result = next( (item for item in my_list if item['name'] == 'Bob'), {} ) print(result) # ๐Ÿ‘‰๏ธ {'id': 2, 'name': 'Bob'} print(result.get('name')) # ๐Ÿ‘‰๏ธ "Bob" print(result.get('id')) # ๐Ÿ‘‰๏ธ 2

The generator expression in the example looks for a dictionary with a name key that has a value of Bob and returns the dictionary.

We used an empty dictionary as a fallback, so if the dictionary in the list has a name key with a value of Bob, the generator expression would return an empty dictionary.

If you need to find all dictionaries in the list that match a condition, use the filter() function.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Alice'}, ] new_list = list( filter(lambda person: person.get('name') == 'Alice', my_list) ) # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'Alice'}, {'id': 3, 'name': 'Alice'}] print(new_list)

If you need to use the get() method on each dictionary in a list, use a for loop to iterate over the list.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] new_list = [] for person in my_list: new_list.append(person.get('name')) print(person.get('name')) print(new_list) # ๐Ÿ‘‰๏ธ ['Alice', 'Bob', 'Carl']

We used a for loop to iterate over the list and on each iteration we used the get() method to get the value of the name property of the dictionary.

The example can be rewritten using a list comprehension.

main.py
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] new_list = [person.get('name') for person in my_list] print(new_list) # ๐Ÿ‘‰๏ธ ['Alice', 'Bob', 'Carl']

The dict.get() method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

The error occurs when we try to call the get() method on a list instead of a dictionary.

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 class's attributes, and recursively of the attributes of its bases.

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

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

  1. AttributeError: 'list' object has no attribute 'startswith'
  2. AttributeError: 'list' object has no attribute 'join'

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

The Python "AttributeError: 'list' object has no attribute 'startswith'" occurs when we call the startswith() method on a list instead of a string.

To solve the error, call startswith() on a string, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute startswith

Here is an example of how the error occurs.

main.py
my_list = ['apple', 'apricot', 'banana'] # โ›”๏ธ AttributeError: 'list' object has no attribute 'startswith' if my_list.startswith('ap'): print('success')

We created a list with 3 elements and tried to call the startswith() method on the list which caused the error.

The startswith() method is string-specific, so we have to call it on a string, and not on a list object.

One way to solve the error is to access the list at a specific index before calling startswith().

main.py
my_list = ['apple', 'apricot', 'banana'] if my_list[0].startswith('ap'): print('string starts with ap')

We accessed the list element at index 0 and called the startswith() method on the string.

If you need to call the startswith() method on each string in a list, use a for loop.

main.py
my_list = ['apple', 'apricot', 'banana'] for word in my_list: if word.startswith('ap'): print('string starts with ap')

We used a for loop to iterate over the list and called the startswith() method on each string.

The str.startswith method returns True if the string starts with the provided prefix, otherwise the method returns False.

The error occurs when we try to call the startswith() method on a list instead of a string.

To solve the error, you either have to correct the assignment of the variable and make sure to call startswith() on a string, or call startswith() on an element in the list that is of type string.

You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call startswith() on each element.

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 class's attributes, and recursively of the attributes of its bases.

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

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

# 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 error 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 class's attributes, and recursively of the attributes of its bases.

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

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev