简体   繁体   中英

TypeError: 'tuple' object does not support item assignment when swapping values

I am writing a simple sort program in python and encounter this error. I want to swap list elements but it returns an error. I am attaching the error and program in question below.

list[i+1] = list[i]
TypeError: 'tuple' object does not support item assignment

Code:

def my_sort(list):
    for index in range(1,len(list)):
        value=list[index]
        i=index-1
        while i>=0:
            if value<list[i]:
                list[i+1] = list[i]
                list[i]=value
                i=i-1
            else:
                break
    return

    input_list=eval(input("Enter list items"))
    my_sort(input_list)
    print(input_list)

Evaluating "1,2,3" results in (1, 2, 3) , a tuple . As you've discovered, tuples are immutable. Convert to a list before processing.

or simply assign the whole tuple itself, instead of changing elements inside tuple.

example: want to add 'count' to 1st element of the 'i-th' tuple :

tup[i] = (tup[i][0] + count, tup[i][1])

To anyone googling this error: check for unwanted commas in your code. For example,

arr = np.zeros(n),
arr[i] = something

will throw this error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM