-1

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

This is why this code doesn't work for me:

list1 = ["unity1", "unity2", "unity3"]
choice1 = str(input("Write your option:")) #user types 1
print("Your choice is ", list1[choice1])

If list1[1] would print "unity2", why doesn't list1[choice1] make the same result because choice1 == 1 ?

I would like it to print "unity2". Do you know any alternative to print one element of a list based on a user choice ? Thank you

JonSG
  • 10,542
  • 2
  • 25
  • 36
wakhan
  • 1
  • You want `choice1 = int(input("Write your option:"))` – Unmitigated Jan 24 '23 at 16:48
  • 1
    *"why doesn't 'list1[choice1]' make the same result"* — Because you're actually doing `list1["1"]`! – deceze Jan 24 '23 at 16:50
  • Think of `indicies` here as numerical ordering of elements in a list, you can't check the numerical ordering with a string, which you define by your `str(input())` – ViaTech Jan 24 '23 at 16:55

1 Answers1

0

You are trying to use a string as an input index. Be aware you need to change the type to Integer using

choice1 = int(choice1)

before doing

print("Your choice is ", list1[choice1])
Erzetah
  • 11
  • 2