W3docs

TypeError: list indices must be integers or slices, not str

This error is usually caused when you try to access an element in a list using a string as the index, rather than an integer.

This error is usually caused when you try to access an element in a list using a string as the index, rather than an integer. For example:

list indices must be integers or slices, not str error example in Python

my_list = [1, 2, 3]
print(my_list['a'])  # This will cause the TypeError

To fix this, you should use an integer to index the list, like this:

Accessing list elements correctly in Python

my_list = [1, 2, 3]
print(my_list[0])  # This will print 1

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

If you want to access the elements of a list using a string key, you should use a dictionary instead of a list. Dictionaries are data structures that allow you to map keys (which can be strings or any other immutable type) to values.

For example:

Accessing dictionary values correctly in Python

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['a'])  # This will print 1