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:
T = (1, 2, 3, 4) # A 4-item tuple print( len(T) ) # Length print( T + (5, 6) ) # Concatenation print( T ) # Indexing, slicing, and more # from w w w .j a v a2 s . c o m
Tuples have type-specific callable methods:
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 # w ww. ja v a 2 s . co m
The tuples cannot be changed once created.
T = (1, 2, 3, 4) # A 4-item tuple T = 2 # Tuples are immutable print( T ) T = (2,) + T[1:] # Make a new tuple for a new value print( T )
Tuples support mixed types and nesting, but they don't grow and shrink because they are immutable:
T = 'test', 3.0, [11, 22, 33] print( T )# from w ww . j a v a 2 s . co m print( T ) print( T.append(4) )
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.