Python Basic Data Structure — Tuple




Tuple







First of all, a tuple is defined by putting “()”, and using “,” to seperate values. Turple is sequencial, meaning the ordering matters.

In [3]:
t=(1,2,3)
t
Out[3]:
(1, 2, 3)

Same as list or ditionary, tuple can hold values of different type

In [4]:
t=("1",2.0,3)
t
Out[4]:
('1', 2.0, 3)
In [5]:
t[0]  #accessing tuple value is the same as list
Out[5]:
'1'

However, you can not alter element in tuple because tuple is considered, because turple is considered immutable. In discrete math, turple usually represent functions and directional object.

In [6]:
t[0]=2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0c0cc230f53e> in <module>()
----> 1 t[0]=2

TypeError: 'tuple' object does not support item assignment

One thing needs to pay attention is when you want to assign a singlton, you need to leave a comma, for example,

In [15]:
t2=(2)   # this won't give you a turple
t2  
Out[15]:
2
In [16]:
type(t2)
Out[16]:
int
In [17]:
t3=(2,)  # you have to leave a comma
t3
Out[17]:
(2,)
In [19]:
type(t3)
Out[19]:
tuple

Write a Comment