TypeError: list indices must be integers or slices, not list in Python
Dung Do Tien
Sep 03 2021
155
Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have a small assignment, I have two arrays, the first contains indexes and the seconds content name and they are the same in size, length. Like this:
superHeroIndex = [0, 1, [2, 3]]
superHeroName = [
'ironman',
'hulk',
['thor', "batman"]
]
for x in superHeroIndex:
print(superHeroName[x])
But I get an exception TypeError: list indices must be integers or slices, not list when I run code above.
ironman
hulk
Traceback (most recent call last):
File "main.py", line 9, in <module>
print(superHeroName[x])
TypeError: list indices must be integers or slices, not list
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any response.
Have 1 answer(s) found.
-
E0
Edwin Valle Villegas Sep 03 2021
Why do you have to nest arrays? why do you not try with this:
superHeroIndex = [0, 1, 2, 3] superHeroName = [ 'ironman', 'hulk', 'thor', 'batman' ] for x in superHeroIndex: print(superHeroName[x])
And it works for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.