Let us learn about python tuple in detail.
Tuple is a Python data structure which are ordered and immutable.Python tuples are written within parentheses. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing.
- Creating a tuple:
- To create a tuple with a single item, we have to add a trailing comma.
Singleton tuple can be created with trailing comma, with or without parentheses.
2. Using tuple constructor:
iterable can be a sequence, a container that supports iteration, or an iterator object.
- iterable can be sequence like list, string.
- iterable can be containers that support iteration like a set,dict
- iterable can contain an iterator object also.
3. Tuple can contain different data types also. It is written within parentheses.
4. Creating an empty tuple.
5.Separating items with commas:
a, b, c or
(a, b, c)
We can create tuple without parentheses also. Actually, the comma makes a tuple. Parentheses are optional except in empty tuple or when they are needed to avoid syntactic ambiguity.
Example: f(a,b,c) — function call with three arguments f((a,b,c))-function call with one argument as 3-tuple. 3-tuple means tuple having 3 elements.
6. Creating a nested tuple
- Tuples are immutable
Tuples do not support item assignment. It will raise TypeError.
- Tuple packing, Tuple unpacking:
The values 1,2,3,’hello’ are packed together in a tuple. This is called
Tuple unpacking is assigning elements in the tuple to variable in a single assignment statement.
Tuple unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the tuple.
Otherwise, it will raise ValueError.
- Accessing tuple elements:
- We can access tuple elements by using index numbers inside square brackets. The first element starts at index 0.
2. Negative Indexing.
We can access using a negative index also. Negative indexing starts from the end. -1 refers to last element.
- Slicing (Range Of Indexes):
We can specify a range of indexes. Returns new tuple containing specified elements.
s[i:j:k] — slice of s from i to j with step k
t[1:3] – Returns a tuple containing element at first and second index.
t[1:] – Returns a tuple containing an element from the first index till the end of the tuple
t[:] – Returns a tuple containing all elements
t[:4] – Returns tuple containing elements from starting till the third index.
Slicing using step argument:
- Modifying tuple:
A tuple is immutable. So we can’t add or remove elements from the tuple. We can only delete tuple.
But we can add items by converting tuple to list and then add items and convert back to a tuple.
If a tuple contains mutable data types like list, we can modify that list.
- Deleting tuple:
we can delete tuple by using
- Joining tuples:
We can combine two tuples using
We can repeat the elements in tuple using
- Tuple Built-in Methods:
Returns the index of the specified element in the tuple. If the element is not in tuple means, it will raise a ValueError. If the specified value occurs more than one-time means, it will return the index of the first occurrence.
x-element to be searched
start,end-The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the tuple.
count(): Returns the count of the specified value in the tuple.
- Membership Test:
We can check whether an item is present in the tuple or not by using
- Comparison Operations:
Tuples compare lexicographically using a comparison of corresponding elements.
Lexicographic order is the way of ordering of words based on the alphabetical order of their component letters.. In case of strings for example consider ABC then all its permutations in lexicographical order will be “ABC, ACB, BAC, BCA, CAB, CBA”
When applied to numbers, lexicographic order is increasing numerical order, i.e. increasing numerical order (numbers read left to right).
1.Equality operation on tuples:
For two tuples to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
2. Order Comparison
Order comparisons between tuples check for the first unequal element in the set. (for example,
[1,2,x] <= [1,2,y] has the same value as
x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example,
[1,2] < [1,2,3] is true).
Order comparisons (<,>,≤,≥) between tuple and other collections raise TypeError.
- Sorting tuple:
sorted() function will sort tuple and return a new sorted list. It won’t modify the original tuple. By default, it will sort in ascending order.
Return Type: List
Sorting tuple in descending order
If the reverse is set to True, it will sort the tuple in descending order.
Sorting tuple using the key parameters.
We can also sort tuple based on the function specified in the key parameter. By default, the sorted function will sort a list of tuples based on the first element. Here we mentioned a user-defined function to take the second element. So, now sorted function sort the list of tuples based on the second element
Tuple Built-in Functions:
len(): Returns the number of elements in the tuple.
min(): Returns the smallest element in the tuple.
max(): Returns the largest element in the tuple.
sum(): Returns the sum of all elements in the tuple.
hash() is supported in immutable sequence types- tuples.
This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.
Attempting to hash an immutable sequence that contains unhashable values will result in
- Iterating through tuple:
We can use
for loop to iterate through tuple.
My other blogs on Python data structures
- Sequence type operations
- Comparison Operation
- Immutable sequence types
- Tuples and sequences
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee