There are cases in which as part of your Data Analysis work you would like to modify one or multiple elements in a Python list.
In this Python programming tutorial we will first breakdown a common beginners mistake in Python: attempting to use the string replace() method on list objects. We’ll then propose several possible solutions to overcome this issue
Understanding the list object has no attribute replace error
Let us start by writing some simple code to reproduce the error. You can try it by yourself in your favorite Python IDE (including Jupyter Notebook).
#define a python list
lang_lst = ['Python','Julia', 'Java', 'R', 'Javascript']
# Attempt to replace one of the list elements.
lang_lst.replace('Javascript', 'JavaScript')
Attempting to changing the list contents using the replace() function will render the following Attribute Error:
AttributeError: 'list' object has no attribute 'replace'
The root cause is simple: replace() is a string function. It simply doesn’t apply to Python lists, tuples, dictionaries, sets or other iterables.
Fixing the Attribute Error when replacing list elements
There are several possible fixes to this issue. All of them will render the same result:
['Python', 'Julia', 'Java', 'R', 'JavaScript']
Using a list comprehension
The most elegant way to replace the list element:
lang_lst = [language.replace('Javascript', 'JavaScript') for language in lang_lst]
print(lang_lst)
Using a for Loop
Looping through the list and modifying its contents:
for language in lang_lst:
language = language.replace('Javascript', 'JavaScript')
print(lang_lst)
Converting to String and replace
Another possibility is to convert our list to a Python string type and then use the replace() function. Then convert the result back to a list object.
lang_lst = ','.join(lang_lst).replace('Javascript', 'JavaScript').split(',')
print(lang_lst)