This article is in continuation of the article series "Jump Start with Python." To read previous articles please refer to the links below:
Now, lets start with part 7 of this article series, we will be discussing tuples in python.
Tuples are immutable lists. Tuples in Python can be written as comma separated values (items) enclosed between parentheses irrespective of their type. Tuples are similar to lists only difference is that it cannot be changed in any way once it is created. This is example of simple tuple in Python:
Creating Tuples
It is very easy to create a tuple in Python, just enclose comma separated values (items) between parentheses.
Syntax: tuple_name=(item1, item2, item3, ---- , itemn)
Some facts about tuples:
- Declaring zero and one element tuple:
If empty parentheses are assigned to a variable then it is termed as zero element tuple.
Syntax: tuple_name=()
One element tuple is declared in Python using the following syntax:
Syntax: tuple_name=("item1", )
- In Python any set of elements which are declared as comma separated values (items) are considered as tuples.
- Indexes for tuples start from 0. Positive indexes start from left to right while negative indexes start from right to left.
- Python also supports slicing index in Tuples which allows accessing multiple elements of tuple at once. Below is an example for slicing in tuples.
Syntax: tuple_name(start_index: end_index)
Sub-tuples
A tuple in Python can have tuples as elements, these sub-tuples may further contain tuple elements as well. Tuples can be recursively created by many sub-tuple structures. Below is example for sub-tuple in Python.
Syntax:
tuple_name=(item1, item2, (sub-item1, sub-item2, --- , sub-itemn), --- , item n)
Basic Operations in Tuples
Tuple Methods
- Length Method: This method is used to determine number of elements or length of a tuple. It consists of one parameter and it is explained as below:
1. tuple_name: It is tuple whose length is to be determined.
Syntax: len(tuple_name)
- Convert to Tuple Method: This method is used to convert a sequence - list or dictionary to tuple. It consists of one parameter and it is explained as below:
1. seq: It is list or dictionary to be converted into tuple.
Syntax: tuple(seq)
- Maximum Method: This method is used to determine maximum element in a tuple. It consists of one parameter and it is explained as below:
1. tuple_name: It is tuple from which maximum element is to be determined.
Syntax: max(tuple_name)
- Minimum Method: This method is used to determine minimum element in a tuple. It consists of one parameter and it is explained as below:
1. tuple_name: It is tuple from which minimum element is to be determined.
Syntax: min(tuple_name)