Last updated: Apr 8, 2024
Reading timeยท23 min
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.
Here is an example of how the error occurs.
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.
To solve the error in this situation, we have to access the list at a specific
index because split
is a method on strings.
my_list = ['bobby_hadz', 'dot_com'] # ๐๏ธ list result = my_list[0].split('_') print(result) # ๐๏ธ ['bobby', 'hadz']
We accessed the list at index 0
to call the split()
method on the first list
element.
If you are trying to call a method on each element in a list, use a for loop to iterate over the list.
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']
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.
my_list = ['bobby', 'hadz'] new_list = [item.upper() for item in my_list] print(new_list) # ๐๏ธ ['BOBBY', 'HADZ']
If you meant to join a list into a string with a separator, call the join()
method on the string separator instead.
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
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.
A common source of the error is trying to use a list.find()
method.
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.
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.
If you need to get the index of a value in a list, use the index()
method.
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.
If you need to add a single element to a list, use the list.append()
method.
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.
a_list = ['bobby'] a_list.extend(['hadz', 'com']) print(a_list) # ๐๏ธ ['bobby', 'hadz', 'com']
If you need to check whether an object contains an attribute, use the
hasattr()
function.
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:
Name | Description |
---|---|
object | The object we want to test for the existence of the attribute |
name | The 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.
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.If you created a list by mistake, track down where the variable gets assigned a list and correct the assignment.
If you meant to use a dictionary, wrap key-value pairs in curly braces.
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.
If you meant to create a class and access its attributes, declare a class and instantiate it.
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.
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.
Here are some examples of solving the error for specific methods. Click on the link to navigate to the subheading.
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.
Here is an example of how the error occurs.
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.
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.
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).
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.
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.
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.
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)
items()
method on a list instead of a dictionary.You can view all the attributes an object has by using the dir()
function.
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.
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'])
.
Here is an example of how the error occurs.
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.
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.
If you need to get the length of an item in the list, access the list at the specific index.
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.
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.
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.
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.
Here is an example of how the error occurs.
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.
lower()
method is string-specific, so we have to call it on a string, and not on a list object.lower()
One way to solve the error is to access the list at a specific index before
calling lower()
.
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.
lower()
on each element in the listIf you need to call the lower()
method on each string in a list, use a list
comprehension.
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.
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.
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.
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
.
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.
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.
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.
Here is an example of how the error occurs.
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.
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()
.
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.
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.
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.
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.
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.
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.
Here is an example of how the error occurs.
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())
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.
One way to solve the error is to access a list element at a specific index.
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.
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.
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.
If you need to find a dictionary in a list, use a generator expression.
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.
name
key with a value of Bobby Hadz
, 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.
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.
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.
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.
Here is an example of how the error occurs.
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.
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()
.
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.
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.
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
.
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.
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.
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.
Here is an example of how the error occurs.
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.
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.
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.
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.
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.
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.
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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
.
get()
method on a list instead of a dictionary.You can view all the attributes an object has by using the dir()
function.
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.
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.
Here is an example of how the error occurs.
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.
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()
.
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.
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
.
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.
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.
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'])
.
Here is an example of how the error occurs.
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.
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.
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()
.
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"
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.
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.