Search code examples
pythonlistindices

How to use variables as list indices?


I have some nested list whose items can be accessed normally with:

list[0][2]

However, when I try to use a variable instead:

uinput = input("Number: )
list[uinput][2]

I get the error:

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

(I have tried it with a dictionary using the same format and it threw the same error)


Solution

  • You're doing it right but you have to convert it to integer first.

    uinput = int(input('Number: '))
    

    Otherwise it's a string and will throw the error you saw.