Tuple
what are tuples? how to create them? when to use them? and tuple methods
Last updated
Was this helpful?
what are tuples? how to create them? when to use them? and tuple methods
Last updated
Was this helpful?
In Python, tuples are similar to except tuples are immutable. While lists are mutable and you can change/modify elements in a tuple after the tuple is created, but you cannot change the elements of a tuple once the tuple is created.
Elements of a tuple are enclosed in parenthesis ()
whereas the elements of list are enclosed in square bracket []
.
The elements of a list are mutable whereas the elements of a tuple are immutable.
It is recommended to use tuple data type when you do not modify data and use list data type when you plan to update/modify/change data in the near future.
Iterating over the elements of a tuple is faster compared to iterating over a list.
It is good to use tuples when
you are not changing your data over time.
There's a strong culture of tuples being for heterogeneous collections.
Iterating over the elements of a tuple is fast so it is recommend to be used when doing iterations of immutable data collections.
Python dictionary requires tuple as one of its components, a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.
You can create a tuple by placing all the elements inside parentheses ()
, separated by commas ,
.
Normally, parentheses are NOT necessary and a tuple can be created as a comma separated elements. However, it is a good practice to use parentheses.
Similar to a list, a tuple elements can contain different data types (string, integer, float, list, another tuple, etc.).
()
A tuple contain integer
A tuple with strings
Tuple with mixed datatypes
Nested tuple
()
A tuple can also be created without using parentheses ()
. This is called tuple packing.
Each element of a tuple can be access and assigned to a new variable.
It is a bit tricky to create a single element tuple. We cannot easily wrap an element inside a parenthesis ()
. This easily worked for a single element list.
You need to convert from simple datatype to complex datatype of tuple, you have to add comma ,
at the end.
You can also access nested list
and nested tuple as well.
You can do concatenation of two tuples with +
operator.
You can also multiple a tuple multiple times with *
operator.
You can check the Jupyter Notebook in GitHub or Colab.
Similar to , you can use index operator []
to access an element in a tuple. Index always starts from ZERO in Python. You can perform all the operations exactly as lists except tuple cannot be modified (immutable)
You can use slicing operations on tuples similar to .