TypeError: 'tuple' object does not support item assignment

前端 未结 4 1626
名媛妹妹
名媛妹妹 2021-01-24 06:20

I\'m trying to write a short program which allows the user to input a list of numbers into an input() function, and then using the add_25 function add 25 to each item in a list.

4条回答
  •  深忆病人
    2021-01-24 07:00

    In Python 2 input() will eval the string and in this case it will create a tuple, and as tuples are immutable you'll get that error.

    >>> eval('1, 2, 3')
    (1, 2, 3)
    

    It is safer to use raw_input with a list-comprehension here:

    inp = raw_input("Please input a series of numbers, divided by a comma:")
    actual_list = [int(x) for x in inp.split(',')]
    

    Or if you're not worried about user's input then simply convert the tuple to list by passing it to list().


    Also note that as you're trying to update the list in-place inside of the function it makes no sense to return the list unless you want to assign another variable to the same list object. Either return a new list or don't return anything.

提交回复
热议问题