Tuples

  • Support all operations for Sequences
  • Immutable, but member objects may be mutable
  • If the contents of a list shouldn't chance, use a tuple to prevent items for accidently being added, changed or deleted
  • Tuples are more efficient than lists due to Python's implementation

In [1]:
x = () # no-item tuple

In [2]:
len(x)


Out[2]:
0

In [3]:
type(x)


Out[3]:
tuple

In [4]:
y = (1,2,3) # three items

In [5]:
y[2]


Out[5]:
3

In [6]:
y[-1]


Out[6]:
3

In [7]:
y[0]


Out[7]:
1

In [8]:
type(y)


Out[8]:
tuple

In [9]:
z = 2, # single-item tuple

In [10]:
z


Out[10]:
(2,)

In [11]:
len(z)


Out[11]:
1

In [12]:
list1 = [10, 20, 30]

In [13]:
a = tuple(list1) # tuple from list
a


Out[13]:
(10, 20, 30)

And YES, they are IMMUTABLE! Watch it:


In [14]:
a


Out[14]:
(10, 20, 30)

In [15]:
del(a[0])


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-49f046f2d244> in <module>()
----> 1 del(a[0])

TypeError: 'tuple' object doesn't support item deletion

In [16]:
a[0] = 11


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-63bb5f4f24d7> in <module>()
----> 1 a[0] = 11

TypeError: 'tuple' object does not support item assignment

In [17]:
a[0]


Out[17]:
10

But, in the case, a list inside a tuple...


In [18]:
a = ([1, 2], 3)

In [19]:
a


Out[19]:
([1, 2], 3)

In [20]:
del(a[0][1]) # a[0][1] is the 1

In [21]:
a


Out[21]:
([1], 3)

In [22]:
t = 12345, 54321, 'tuple!'

In [23]:
t


Out[23]:
(12345, 54321, 'tuple!')

In [24]:
# tuples may be nested
c = a, (1, 2, 3, 4)
c


Out[24]:
(([1], 3), (1, 2, 3, 4))

In [25]:
t = 'abc', 1000, 3.14

In [26]:
x, y, z = t # tuple packing
x


Out[26]:
'abc'

In [32]:
t1 = (10, 20, 30, 100, 1000, 10, 20, 20)

In [33]:
t1.count(10)


Out[33]:
2

In [34]:
t1.count(20)


Out[34]:
3

In [35]:
t1.index(10)


Out[35]:
0

In [36]:
t1.index(100)


Out[36]:
3

In [37]:
100 in t1


Out[37]:
True

In [38]:
3 in t1


Out[38]:
False

In [39]:
3 not in t1


Out[39]:
True

In [40]:
for name in ('John', 'Mary'):
    print('Hello', name)


Hello John
Hello Mary

In [45]:
max(t1)


Out[45]:
1000

In [46]:
min(t1)


Out[46]:
10

In [47]:
sorted(t1) # return a new sorted list, does not sorte the tuple itself! Remember: immutable!


Out[47]:
[10, 10, 20, 20, 20, 30, 100, 1000]

In [48]:
t1


Out[48]:
(10, 20, 30, 100, 1000, 10, 20, 20)

In [49]:
sum(t1)


Out[49]:
1210

In [ ]: