Python - Data Type Tuples

Introduction

The tuple object is roughly like a list.

The tuples are cannot-be-changed sequences.

They are immutable.

They're used to represent fixed collections of items.

The tuples are normally coded in parentheses and they support arbitrary types, arbitrary nesting, and the usual sequence operations:

Demo

T = (1, 2, 3, 4)      # A 4-item tuple 
print( len(T) )       # Length 
print( T + (5, 6) )   # Concatenation 
print( T[0] )         # Indexing, slicing, and more
# from   ww w. j av  a2  s .  c o  m

Result

Tuples have type-specific callable methods:

Demo

T = (1, 2, 3, 4)            # A 4-item tuple 
print( T.index(4) )                  # Tuple methods: 4 appears at offset 3 
print( T.count(4) )                  # 4 appears once
#  ww w  .j av a 2 s .  com

Result

The tuples cannot be changed once created.

Demo

T = (1, 2, 3, 4) # A 4-item tuple 
T[0] = 2         # Tuples are immutable 
print( T )
T = (2,) + T[1:] # Make a new tuple for a new value 
print( T )

Result

Tuples support mixed types and nesting, but they don't grow and shrink because they are immutable:

Demo

T = 'test', 3.0, [11, 22, 33] 
print( T[1] )#  ww  w. java 2 s. c  om
print( T[2][1] )
print( T.append(4) )

Result

Why Tuples?

Tuples are not used as often as lists.

If you pass a collection of objects around your program as a list, it can be changed anywhere.

If you use a tuple, it cannot be changed.

Tuples provide an integrity constraint.