Search code examples
pythonstringlistintegerindices

list indices must be integers, not str


class targil4(object):
    def plus():
        x=list(raw_input('enter 4 digit Num '))
        print x
        for i in x:
            int(x[i])
            x[i]+=1
        print x

    plus()

this is my code, I try to get input of 4 digits from user, then to add 1 to each digit, and print it back. When I run this code i get the massage:

Traceback (most recent call last):
['1', '2', '3', '4']
  File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 1, in <module>
class targil4(object):
  File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 10, in   targil4
    plus()
  File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 6, plus
  int(x[i])
TypeError: list indices must be integers, not str

Process finished with exit code 1

Solution

  • I believe you may get more out of an answer here by actually looking at each statement and seeing what is going on.

    # Because the user enters '1234', x is a list ['1', '2', '3', '4'],
    # each time the loop runs, i gets '1', '2', etc.
    for i in x:
        # here, x[i] fails because your i value is a string.
        # You cannot index an array via a string. 
        int(x[i])
        x[i]+=1
    

    So we can "fix" this by adjusting the code by our new understanding.

    # We create a new output variable to hold what we will display to the user
    output = ''
    for i in x:
        output += str(int(i) + 1)
    print(output)