Understanding Python Tuples: A Beginner's Guide to Immutable Sequences
Table of Content:
A collection of ordered and immutable objects is known as a tuple. Tuples and lists are similar as they both are sequences. Though, tuples and lists are different because we cannot modify tuples, although we can modify lists after creating them, and also because we use parentheses to create tuples while we use square brackets to create lists.
Placing different values separated by commas and enclosed in parentheses forms a tuple. For instance,
Example
tuple_1 = ("Python", "tuples", "immutable", "object") tuple_2 = (23, 42, 12, 53, 64) tuple_3 = "Python", "Tuples", "Ordered", "Collection"
We represent an empty tuple by two parentheses enclosing nothing.
Empty_tuple = ()
We need to add a comma after the element to create a tuple of a single element.
Tuple_1 = (50,)
Tuple indices begin at 0, and similar to strings, we can slice them, concatenate them, and perform other operations.
Create a Tuple
All the objects (elements) must be enclosed in parenthesis (), each separated by a comma, to form a tuple. Although using parenthesis is not required, it is recommended to do so.
Whatever the number of objects, even of various data types, can be included in a tuple (dictionary, string, float, list, etc.).
Code
# Python program to show how to create a tuple # Creating an empty tuple empty_tuple = () print("Empty tuple: ", empty_tuple) # Creating tuple having integers int_tuple = (4, 6, 8, 10, 12, 14) print("Tuple with integers: ", int_tuple) # Creating a tuple having objects of different data types mixed_tuple = (4, "Python", 9.3) print("Tuple with different data types: ", mixed_tuple) # Creating a nested tuple nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6)) print("A nested tuple: ", nested_tuple)
Output
Empty tuple: () Tuple with integers: (4, 6, 8, 10, 12, 14) Tuple with different data types: (4, 'Python', 9.3) A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not mandated to build tuples. Tuple packing is the term for this.
Example
# Python program to create a tuple without using parentheses # Creating a tuple tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"] # displaying the tuple created print(tuple_) # Checking the data type of object tuple_ print( type(tuple_) ) # trying to modify tuple_ try: tuple_[1] = 4.2 except: print( TypeError )
Output
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
It can be challenging to build a tuple with just one element.
Placing just the element in parentheses is not sufficient. It will require a comma after the element to be recognized as a tuple.
Example
# Python program to show how to create a tuple having a single element single_tuple = ("Tuple") print( type(single_tuple) ) # Creating a tuple that has only one element single_tuple = ("Tuple",) print( type(single_tuple) ) # Creating tuple without parentheses single_tuple = "Tuple", print( type(single_tuple) )
Output
Repetition Tuples in Python
Example
# Python program to show repetition in tuples tuple_ = ('Python',"Tuples") print("Original tuple is: ", tuple_) # Repeting the tuple elements tuple_ = tuple_ * 3 print("New tuple is: ", tuple_)
Output
Original tuple is: ('Python', 'Tuples') New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Tuple does not provide methods to add or delete elements, and there are only the following two choices.
Examples of these methods are given below.
Example
# Python program to show how to tuple methods (.index() and .count()) work # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered") # Counting the occurrence of an element of the tuple using the count() method print(tuple_.count('Ordered')) # Getting the index of an element using the index() method print(tuple_.index('Ordered')) # This method returns index of the first occurrence of the element
Output
2 2
Tuple Membership Test
Using the in keyword, we can determine whether an item is present in the given tuple or not.
Example
# Python program to show how to perform membership test for tuples # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered") # In operator print('Tuple' in tuple_) print('Items' in tuple_) # Not in operator print('Immutable' not in tuple_) print('Items' not in tuple_)
Output
True False False True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.
Example
# Python program to show how to iterate over tuple elements # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable") # Iterating over tuple elements using a for loop for item in tuple_: print(item)
Output
Python Tuple Ordered Immutable
Advantages of Tuple over List
Tuples and lists are employed in similar contexts because of how similar they are. A tuple implementation has several benefits over a list, though. The following are a few of the primary benefits:
- We generally employ lists for homogeneous data types and tuples for heterogeneous data types.
- Tuple iteration is quicker than list iteration because tuples are immutable. There is such a modest performance improvement.
- Tuples with immutable components can function as the key for a Python dictionary object. This feature is not feasible with lists.
- Collecting data in a tuple will ensure that it stays write-protected if it never changes.
Points to remember for Tuples
- Tuples are immutable Python sequences, i.e. you cannot change elements of a tuple in place.
- Tuples' items are indexed.
- Tuples store a reference at each index.
- Tuples can be indexed sliced and its individual items can be indexed.
- len (T) returns count of tuple elements.
- Tuple manipulation functions are: len(), max(), min(), and tuple().