skip to Main Content

Following a tutorial and this program won’t run as expected

my_tuple = {'a', 'p', 'p', 'l', 'e'}

print(my_tuple.index('p'))

Whenever I run this program, the terminal always outputs:

    print(my_typle.index('p'))
AttributeError: 'set' object has no attribute 'index'

Does VS Code’s Python not run these functions or, am I doing something wrong?

2

Answers


  1. You are trying to access index method of set object, which does not exist. You should create a list object instead:

    my_tuple = ['a', 'p', 'p', 'l', 'e']
    
    print(my_tuple.index('p'))
    
    Login or Signup to reply.
  2. That’s not a tuple, it’s a set. A tuple uses Parentheses and an set uses Curly Brackets.

    https://www.w3schools.com/python/python_tuples.asp
    https://www.w3schools.com/python/gloss_python_set.asp

    Proper code:

    my_tuple = ('a', 'p', 'p', 'l', 'e')
    
    print(my_tuple.index('p'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search