NickSentowski NickSentowski - 7 days ago 4
Python Question

Python 2D Lists in For Loops

I have built a 2D list (I still want to call it an array) to hold information about currency tokens as such:

Token = [["P",0,.01,"Penny"],["N",0,.05,"Nickel"],["D",0,.10,"Dime"],["Q",0,.25,"Quarter"]]

When I try to read the value of a token using this code:

for i in Token:
print (Token[i][3])

I am given an error:

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

I'm not sure I understand the error, and have not had much success searching online for a solution. Any help you can offer would be greatly appreciated.

If it helps, code for the whole project is on GitHub.


You are using a for-each loop which, in Python, will give you the item in the list, not an index. Also, you are using a set of sets, which is not valid syntax. Therefore, keep a list of sets and just just use one index:

Token =  [["P",0,.01,"Penny"],["N",0,.05,"Nickel"],["D",0,.10,"Dime"],["Q",0,.25,"Quarter"]]

for i in Token: