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)
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)
Do not use the name
list
for a list. I have usedmylist
below.for s in mylist:
assigns elements ofmylist
tos
i.es
takes the value 'abc' in the first iteration and 'def' in the second iteration. Thus,s
can't be used as an index inmylist[s]
.Instead, simply do:
for s in list
will produce the items of the list and not their indexes. Sos
will be'abc'
for the first loop, and then'def'
.'abc'
could only be a key to a dict, not a list index.In the line with
t
fetching the item by index is redundant in python.Output:
This is what you want exactly.
Output:
it should be:
i think you want:
enumerate
give index and elementNote: using list as variable name is bad practice. its built in function
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 (firstabc
, thendef
).It looks like what you're trying to do is essentially this:
This is using a Python construct called list comprehension.