Immutable Sequence Types in Python
Immutable Sequence Types
Mutable and immutable objects are treated differently in python. Immutable objects are faster to access and are costlier to change because it needs the creation of a copy.
Whereas mutable objects are easy to change.
In other words, Immutable objects cannot be changed after their creation. Example of immutable sequence in python is Tuple().
Immutable Sequence Types in Python
In Python the data structure or we can say sequences are defined into two categories –
- Mutable Sequences
- Immutable Sequences
Mutable sequences can be changed after their creation while immutable sequences can’t be updated however there are some tricks to update the immutable sequences. So, due to above characteristics it can be referred as immutable sequences are read-only and mutable sequences are both read and write compatible.
There are some immutable sequence types in python:
- Tuple
- String
Tuple
>>> companies = (['tata','wipro'],'accenture') >>> companies (['tata', 'wipro'], 'accenture') >>> type(companies) <class 'tuple'> >>> companies[0][1]='tcs' >>> companies (['tcs', 'wipro'], 'accenture') >>> companies[1]='cognizant' Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> companies[1]='cognizant' TypeError: 'tuple' object does not support item assignment
String
>>> String = "prepinsta"
>>> String[1] ='p'
>>> print(String)
Traceback (most recent call last):
File "/home/main.py", line 2, in
String[1] ='p'
TypeError: 'str' object does not support item assignment
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment