Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: list indices must be integers, not str Python

list[s] is a string. Why doesn't this work?

The following error appears:

TypeError: list indices must be integers, not str

list = ['abc', 'def']
map_list = []

for s in list:
  t = (list[s], 1)
  map_list.append(t)
like image 838
kerschi Avatar asked Dec 27 '14 13:12

kerschi


People also ask

How do you fix TypeError list indices must be integers or slices not list?

The way to avoid encountering this error is to always assign an integer value to the variable. In the above example, we have declared a list with the name “list1” and an index variable to access the value of list with the name 'index' and given value “1” as a string, not an integer.

How do you fix TypeError string indices must be integers?

To solve TypeError: string indices must be integers; we should reference our dictionary instead of “ele“. We can access elements in our dictionary using a string. This is because dictionary keys can be strings. We don't need a for loop to print out each value.

What does list indices must be integers or slices not list mean?

This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function.

How do you fix list indices must be integers or slices not float?

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)] .


1 Answers

When you iterate over a list, the loop variable receives the actual list elements, not their indices. Thus, in your example s is a string (first abc, then def).

It looks like what you're trying to do is essentially this:

orig_list = ['abc', 'def']
map_list = [(el, 1) for el in orig_list]

This is using a Python construct called list comprehension.

like image 72
NPE Avatar answered Nov 02 '22 16:11

NPE