The Python Tuple is almost similar to a List, except that these are immutable, and Lists are mutable. It means Once we declare the Tuple, we cannot change the values or items inside it, something like the Constant keyword in other programming languages.
What is a tuple in Python?
A Python Tuple is a sequence of multiple values in an ordered sequence. Tuples are declared using Open and Closed Parenthesis ( ). Unlike Strings, Tuple allows us to store different data types such as integer, float, string, etc.
How to Declare Python Tuple?
To declare an empty Tuple with no values, use TupleName = ().
Like any other collection, we have to declare the elements where commas separate each item. Even to declare this object with one item, we have to specify a comma after the item.
For instance: TupleName = (245,). If you forgot to add a comma, it is an integer type (Not a Tuple). The following is the list of possible ways to declare a String, Mixed, Nested, and List Tuples in Python.
StringTup = (‘apple’, ‘Orange’, ‘Grape’, ‘Mango’) is a string tuple that contains four string values.
MixedTup = (‘apple’, 2, 3.50, ‘Mango’) is a mixed one that contains one integer, one float, and two integer values.
NestedTup = (‘Gateway’, ‘Tutorial’, (1, 2, 3) ) is an example of one inside another (Nested).
ListTup = (‘Py’, ‘Tutorial’, [1, 2, 3] ) is an example of List inside it.
How to access Python Tuple items?
We can access the Tuple items using indexes. Using the index, we can access each item present in it separately. The index value starts at 0 and ends at n-1, where n is the size. Using the Negative numbers as an index, it starts looking for elements from right to left.
For instance, if a class stores 5 elements, then the index starts at 0 and ends with 4. To access the first value, use TupName; to access the fifth value, use TupName. Let us see the integer data type example for better understanding:
x = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Positive Indexing print(x) print(x) print(x) print('=======\n') # Negative Indexing print(x[-2]) print(x[-4]) print(x[-8]) print('=======\n') MixedTup = ((1, 2, 3), [4, 5, 6], 'Learn') print(MixedTup) print(MixedTup) print(MixedTup) print(MixedTup)
1 5 9 ======= 8 6 2 ======= 1 4 L n
Iterating Python Tuple
The For Loop is the most popular way to traverse the elements. The following statement helps to iterate the object and print the items inside the Fruits.
Fruits = ('Apple', 'Orange', 'Grape', 'Banana', 'Strawberry','Cherry', 'Kiwi') for Fruit in Fruits: print(Fruit)
In this example, we show the use of Arithmetic Operators on Tuple to perform arithmetic operations.
X = (1, 2, 3) Y = (4, 5, 6) Sum = X + Y print(Sum) # Using * Operator Z = X * 3 print(Z)
(1, 2, 3, 4, 5, 6) (1, 2, 3, 1, 2, 3, 1, 2, 3)
From the above output, you can observe that
- The + operator is concatenating
- * operator is repeating for a given number of times. Here it is three times
Python Tuple slice
In Tuple Slice syntax, the first integer value is the index position where the slicing starts, and the second one is the index position where the slicing end.
The slicing goes up to the second integer value but does not include the value at this index position. For instance, if we specify tuple_exmp[1:4], then slicing starts at index position 1 and ends at position 3 (not 4).
x = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Slicing using two indexes a = x[2:6] print(a) # Slicing using First b = x[:6] print(b) # Using Second c = x[2:] print(c) # Without using two d = x[:] print(d) # Slice using Negative e = x[-3:] print(e) # Slice using Negative f = x[:-2] print(f)
(3, 4, 5, 6) (1, 2, 3, 4, 5, 6) (3, 4, 5, 6, 7, 8, 9) (1, 2, 3, 4, 5, 6, 7, 8, 9) (7, 8, 9) (1, 2, 3, 4, 5, 6, 7)
- If there is no first index, then Python Slicing starts from the beginning.
- If the second index is not provided, Slicing starts from the first index and continues to the last.
- Using the Negative numbers as the index, Slicing starts from right to left.
Altering Tuple items
It won’t allow altering the tuple items inside it. Let’s see what happens when we do that.
Analysis: Within the First statement, We assigned a new value at index position two. Since it is immutable, the output is throwing a Type Error. Within the Second statement, We assigned a new value to this inside another at index position one.
Although it is a Nested tuple, the output throws a Type Error because it is immutable. In the Third statement, We assigned a new value at position , which is List inside it. Since List is mutable, we successfully changed the value from 5 to 14.
Python Tuple Methods
It provides the following methods. The tuple() method helps to convert the String or Lists into Tuple.
The min function helps us to find the Smallest or minimum item and the max function finds the Largest item or largest item.
The Len method finds or calculates the Length or Number of items, and the sorted method helps to sort the elements in ascending order. The index function returns the index position of a specified value.
The sum function calculates the sum of all items inside the given one. And the count function counts the total number of times the specified value is repeated.
In the below program, we are applying all the Tuple methods. It might help to see all the functions.
FruitsTP = ('Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry') tp = (9, 4, -5, 0, 22, -1, 2, 14) #Finding Sum of all item in a using Sum() Method print('Sum of all items in a tp = ', sum(tp)) #Calculating Length of a using len() Method print('Length of a FruitsTP = ', len(FruitsTP)) print('Length of a tp = ', len(tp)) #Finding Minimum item in a using min() Method print('Minimum item in a FruitsTP = ', min(FruitsTP)) print('Minimum item in a tp = ', min(tp)) #Finding Maximum item in a using max() Method print('Maximum item in a FruitsTP = ', max(FruitsTP)) print('Maximum item in a tp = ', max(tp)) # Using Sorted() Method print('After Sorting FruitsTP = ', sorted(FruitsTP)) print('After Sorting tp = ', sorted(tp)) # Index position of an item in a using index() Method print('The Index position of Banana = ', FruitsTP.index('Banana')) print('The Index position of -1 = ', tp.index(-1)) # Counting items in a using count() Method tp2 = (9, 4, 1, 4, 9, -1, 2, 4) print('Number of Times 4 is repeated = ', tp2.count(4)) print('Number of Times 9 is repeated = ', tp2.count(9)) # Converting List tp3 = [1, 2, 3, 4, 5] print(tuple(tp3))
Sum of all items in a tp = 45 Length of a FruitsTP = 6 Length of a tp = 8 Minimum item in a FruitsTP = Apple Minimum item in a tp = -5 Maximum item in a FruitsTP = Orange Maximum item in a tp = 22 After Sorting FruitsTP = ['Apple', 'Banana', 'Blackberry', 'Grape', 'Kiwi', 'Orange'] After Sorting tp = [-5, -1, 0, 2, 4, 9, 14, 22] The Index position of Banana = 2 The Index position of -1 = 5 Number of Times 4 is repeated = 3 Number of Times 9 is repeated = 2 (1, 2, 3, 4, 5)