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:
- >>> a = "tea"
- >>> a = "Tea"
- >>> print(a[0])
- T
- >>> a[0] = "S"
- Traceback (most recent call last):
- File "", line 1, in
- a[0] = "S"
- TypeError: 'str' object does not support item assignment
2. Tuple example:
- >>> a = (1.10,2018,"tea")
- >>> a[2] = "sea"
- Traceback (most recent call last):
- File "", line 1, in
- a[2] = "sea"
- 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)
- >>> m = [1,2,3]
- >>> id(m)
- 46873096L
- >>> n = m
- >>> id(m) == id(n)
- >>> True
- >>> m.pop()
- 3
- >>> id(m)
- 46873096L
- >>> print m
- [1, 2]
- >>> print n
- [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)
- >>> a = 10
- >>> b = a
- >>> id(a)
- 32168864L
- >>> id(a) == id(b)
- True
- >>> a = a+1
- >>> id(a)
- 32168840L
- >>> id(a) == id(b)
- 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.
Articoli simili
- How to fix “str” object is not callable when using set() function in Python 3.6.4
- Cosa significa 'Errore: Può solo concatenare str (non "int") a str' significa in Python?
- Come risolvere TypeError: unsupported operand type(s) per -: 'str' e 'str' in Python
- What does HDR10 support mean in a smartphone display?