Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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) 
like image 996
John Connor Avatar asked Oct 12 '11 05:10

John Connor


People also ask

Do tuples support item assignment?

Tuples are immutable objects. “Immutable” means you cannot change the values inside a tuple. You can only remove them.

How do you assign a value to a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Which object does not support item assignment in Python?

The Python "TypeError: 'type' object does not support item assignment" occurs when we assign a data type to a variable and use square brackets to change an index or a key. To solve the error, set the variable to a mutable container object, e.g. my_list = [] .

What will be error if we trying to change update tuple element?

The underlying problem, is that changing the value of a tuple is a violation of contract. You should not try doing it. Since you can have any object in a tuple, there are loopholes you can exploit, but then you get the kind of weird behaviour you are observing. Tuple items should be frozenset instead of set .


1 Answers

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

like image 190
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 18:10

Ignacio Vazquez-Abrams