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)
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.
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.
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.
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)] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With