How to Fix AttributeError: ‘list’ object has no attribute ‘clear’

Diagram of How to Fix AttributeError: 'list' object has no attribute 'clear'

Diagram

AttributeError: ‘list’ object has no attribute ‘clear’ error occurs when you are running Python version below 3.3.

Reproduce the error

Assuming that you are using Python version below 3.3.

new_list = [1, 2, 3]
print(new_list)

new_list.clear()
print(new_list)

Output

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

How to fix the error?

To fix the error, upgrade to the latest Python version. With the release of Python 3.3, list clear() and list copy() methods were introduced.

Using Python 3.3 or above

Since my current version is 3.9, I can use the clear() method without any error.

new_list = [1, 2, 3]
print(new_list)

new_list.clear()
print(new_list)

Output

Using Python 3.3 or above

Using Python 2 or below 3.3

If you are using Python 2.x or below 3.3, you can clear the list using del statement and slicing.

new_list = [1, 2, 3]
print(new_list)

del new_list[:]
print(new_list)

Output

Using Python 2 or below 3.3

Conclusion

If you are using Python 2.x, then you can use the slicing and del statement. 

If you are using Python 3.3 or above, use the list.clear() method.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.