Python short course: Tuples in Action

 Python tuple is a collectio type. Tuples are immutable (cannot be changed in place). The tuple is similar but different from the list.

Basic operation


In [1]: (1, 2) + (3, 4)
Out[1]: (1, 2, 3, 4)

In [2]: (1, 2) * 4
Out[2]: (1, 2, 1, 2, 1, 2, 1, 2)

In [3]: T = (1, 2, 3, 4)

In [4]: T[0], T[1:3]
Out[4]: (1, (2, 3))

A tuple is immutable, but a list can change its element


In [5]: T = (1., [2, 3], 4)

In [6]: T[0]
Out[6]: 1.0

In [7]: T[0] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-0e6a27ccfe54> in <module>
----> 1 T[0] = 5

TypeError: 'tuple' object does not support item assignment

In [8]: T[1][0] = 'changed'

In [9]: T
Out[9]: (1.0, ['changed', 3], 4)

Reference: 

Lutz, M. Learning Python (5th ed.) O'Reilly, 2013, 1594

Comments

Popular posts from this blog

Lab's weekly topic - week 50 2023 - Detailed explanation for encoder of U-Net

Lab's recommendation: Awesome books to learn machine learning and AI (continue updating)