Tuple in Python
Tuple in Python
Tuple:
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a Tuple :
Creating a tuple is as simple as putting different comma-separated values.
T=( 1,55,”Baby",a12);
Empty Tuple :
The empty tuple is written as two parentheses containing nothing
T=( );
To write a tuple containing a single value you have to include a comma, even though there is only one
value .
T= (77,);
Concatenation of Tuples: (Addition)
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done
by the use of ‘+’ operator.
Only the same datatypes can be combined with concatenation, an error arises if a list
and a tuple are combined.
Ex:
T1 =(1,2,3);
T2=(4,5,6);
Print(T1+T2);
Output
(1,2,3,4,5,6)
Output
True
False
Repetition:( Multiplication)
Multiplying a tuple by any integer, x will simply create another tuple with all the elements
from the first tuple being repeated x number of times. For example, t*3 means, elements of
tuple t will be repeated 3 times.
>>> t = (2, 5)
>>> print (t*3);
Output
(2,5,2,5,2,5)
We can use the for loop to iterate over the elements of a tuple. For example,
languages = ('Python', 'Swift', 'C++')
Output
Python
Swift
C++
>>> t = (1, 4, 2, 7, 3, 9)
Output
We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with a list. So there
is a slight performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected