Python 6-1 220510 092851
Python 6-1 220510 092851
M. Asif Farooq
1/8
Mutable and Immutable Objects
An object holds the data and has operations that can manipulate
the data.
Numbers, strings, lists and tuples are objects.
Objects that can be changed in places are called mutable.
Objects that cannot be changed in place are called immutable.
2/8
Defining Tuples
3/8
Tuples: Examples
In [54]: t = (3, 4 , 5)
In [55]: print(len(t))
3
In [56]: print(max(t))
5
In [57]: print(min(t))
3
In [58]: print(sum(t))
12
In [59]: t[0]
Out[59]: 3
In [60]: t[0] = t[0] + 3
Traceback (most recent call last):
File "C:1 2760786003402.py ”, line1, in < cellline : 1 >
t[0] = t[0] + 3
TypeError: ’tuple’ object does not support item assignment
4/8
Comments on Tuples
5/8
Examples: Converting Lists or Strings into Tuples
In [1]: tuple([’fruits’, ’vegetables’])
Out[1]: (’fruits’, ’vegetables’)
In [3]: tuple("spam")
Out[3]: (’s’, ’p’, ’a’, ’m’)
7/8
Examples: Tuples
In [10]: t = (2,3,1,3)
In [11]: print(t[1])
3
In [12]: t.index(3)
Out[12]: 1
In [15]: t.count(3)
Out[15]: 2
In [16]: len(t)
Out[16]: 4
In [17]: sum(t)
Out[17]: 9
In [18]: t + (7,5)
Out[18]: (2, 3, 1, 3, 7, 5)
In [19]: t*2
Out[19]: (2, 3, 1, 3, 2, 3, 1, 3)
8/8