QNA > W > What Does 'Str' Object Does Not Support Item Assignment' Error Mean In Python?

What does 'str' object does not support item assignment' error mean in python?

TypeError: <> object does not support item assignment.

such error usually comes while we are modifying immutable object. Because immutable objects doesn’t allow modification after creation.

ex:

1. string example:

  1. >>> a = "tea" 
  2. >>> a = "Tea" 
  3. >>> print(a[0]) 
  4. >>> a[0] = "S" 
  5. Traceback (most recent call last): 
  6. File "", line 1, in  
  7. a[0] = "S" 
  8. TypeError: 'str' object does not support item assignment 

2. Tuple example:

  1. >>> a = (1.10,2018,"tea") 
  2. >>> a[2] = "sea" 
  3. Traceback (most recent call last): 
  4. File "", line 1, in  
  5. a[2] = "sea" 
  6. TypeError: 'tuple' object does not support item assignment 

So this shows that immutable objects does not allow to modify after creation.

Internally, how it works for mutable or immutable datatypes? Let's see below examples :

  • List (mutable)
  1. >>> m = [1,2,3] 
  2. >>> id(m) 
  3. 46873096L 
  4. >>> n = m 
  5. >>> id(m) == id(n) 
  6. >>> True 
  7. >>> m.pop() 
  8. >>> id(m) 
  9. 46873096L 
  10. >>> print m 
  11. [1, 2] 
  12. >>> print n 
  13. [1, 2] 

List is mutable. because id of list is same before and after modification. i.e. list allows us to modify its data.

  • int (immutable)
  1. >>> a = 10 
  2. >>> b = a 
  3. >>> id(a) 
  4. 32168864L 
  5. >>> id(a) == id(b) 
  6. True 
  7. >>> a = a+1 
  8. >>> id(a) 
  9. 32168840L 
  10. >>> id(a) == id(b) 
  11. False 

int is immutable because when we change its value, object’s location in memory get changed. It does not allow to modify data in same memory location.

Objects of built-in types like (int, float, bool, str, tuple, dictionary key) are immutable.

Objects of built-in types like (list, set, dict) are mutable.

Di Melicent Ensey

Come sistemare le mappe mancanti su GMOD :: Un caso di rottura del COVID-19 Delta per i vaccinati è simile al "raffreddore" e quindi non c'è nulla di cui preoccuparsi?
Link utili