Python Tuples
Python Tuple is a collection of Python Programming objects much similar as a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by ‘commas ‘. Although it is not necessary, it is more popular to define a tuple by closing the sequence of values in parentheses. This helps in understanding the Python tuples more easily.
Creating a Tuple
In Python Programming, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping the data sequence.
Note: Creation of Python tuple without the use of parentheses is known when Tuple Packing.Â
Python Program to Demonstrate the Addition of Elements in a Tuple.
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple
# with the use of string
Tuple1 = ('Codes', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Codes')
print("\nTuple with the use of function: ")
print(Tuple1)
Output:Â
Initial empty Tuple: () Tuple with the use of String: ('codes', 'For') Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('C', 'o', 'd', 'e', 's')
Creating a Tuple with Mixed Datatypes.
Python Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# Creating a Tuple
# with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Codes')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'code')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
# Creating a Tuple
# with repetition
Tuple1 = ('Codes',) * 3
print("\nTuple with repetition: ")
print(Tuple1)
# Creating a Tuple
# with the use of loop
Tuple1 = ('Codes')
n = 5
print("\nTuple with a loop")
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)
Output:
Tuple with Mixed Datatypes: (5, 'Welcome', 7, 'Codes') Tuple with nested tuples: ((0, 1, 2, 3), ('python', 'Code')) Tuple with repetition: ('Codes', 'Codes', 'Codes') Tuple with a loop ('Codes',) (('Codes',),) ((('Codes',),),) (((('Codes',),),),) ((((('Codes',),),),),)
Time complexity: O(1)
Auxiliary Space : O(n)
Python Tuple Operations
Here, below are the Python tuple operations.
- Accessing of Python Tuples
- Concatenation of Tuples
- Slicing of Tuple
- Deleting a Tuple
Accessing of Tuples
In Python Programming, Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by property in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
Note: In unpacking of tuple number of variables enabled the left-hand side should be equal to a number of values in given tuple a.
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Codes")
print("\nFirst element of Tuple: ")
print(Tuple1[0])
# Tuple unpacking
Tuple1 = ("Codes", "For", "codes")
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
Output:
First element of Tuple: C Values after unpacking: Codes For Codes
Time complexity: O(1)
Space complexity: O(1)
Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other arithmetic operations do not apply enabled Tuples.Â
Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a tuple are combined.
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Codes', 'For', 'Codes')
Tuple3 = Tuple1 + Tuple2
# Printing first Tuple
print("Tuple 1: ")
print(Tuple1)
# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)
# Printing Final Tuple
print("\nTuples after Concatenation: ")
print(Tuple3)
Output:Â
Tuple 1: (0, 1, 2, 3) Tuple2: ('Codes', 'For', 'codes') Tuples after Concatenation: (0, 1, 2, 3, 'Codes', 'For', 'codes')
Time Complexity: O(1)
Auxiliary Space: O(1)
Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to fetch a set of elements.Â
Note- Negative Increment values can also have used to reverse the sequence of Tuples.Â
# Slicing of a Tuple
# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('CODESFORCODES')
# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])
# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])
# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])
Output:Â
Removal of First Element: ('O', 'D', 'E', 'S', 'F', 'O', 'R', 'C', 'O', 'D', 'E', 'S') Tuple after sequence of Element is reversed: ('S', 'E', 'D', 'O', 'C', 'R', 'O', 'F', 'S', 'E', 'D', 'O', 'C') Printing elements between Range 4-9: ('S', 'F', 'O', 'R', 'C')
Time complexity: O(1)
Space complexity: O(1)
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets deleted by the use of del() method.Â
Note- Printing of Tuple after deletion results in an Error.Â
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
Output
Traceback (most recent call last): File "/home/efa50fd0709dec08434191f32275928a.py", line 7, in print(Tuple1) NameError: name 'Tuple1' is not defined
Built-In Methods
Built-in-Method | Description |
---|---|
index( ) | Find in the tuple and returns the index of the given value where it’s available |
count( ) | Returns the frequency of occurrence of a specified value |
Built-In Functions
Built-in Function | Description |
---|---|
all() | Returns true if all elements are true or if tuple is empty |
any() | return true if any element of the tuple is true. if tuple is empty, return false |
len() | Returns length of the tuple or size of the tuple |
enumerate() | Returns enumerate object of tuple |
max() | return maximum element of given tuple |
min() | return minimum element of given tuple |
sum() | Sums up the numbers in the tuple |
sorted() | input elements in the tuple and return a new sorted list |
tuple() | Convert an iterable to a tuple. |
Tuples VS Lists:
Similarities | Differences |
Functions that can have used for both lists and tuples: len(), max(), min(), sum(), any(), all(), sorted() |
Methods that cannot have used for tuples: append(), insert(), remove(), pop(), clear(), sort(), reverse() |
Methods that can be have used for both lists and tuples: count(), Index() |
we generally use ‘tuples’ for heterogeneous (different) data types and ‘lists’ for homogeneous (similar) data types. |
Tuples can be stored in lists. | Iterating through a ‘tuple’ is faster than in a ‘list’. |
Lists can be stored in tuples. | ‘Lists’ are mutable whereas ‘tuples’ are immutable. |
Both ‘tuples’ and ‘lists’ can be nested. | Tuples that contain immutable elements can have used when a key for a dictionary. |
Python Tuples – FAQs
What are the Characteristics of Tuples in Python?
Characteristics of Tuples:
- Immutable: Once created, the elements of a tuple cannot be modified, added, or removed.
- Ordered: Tuples maintain the order of elements, and elements can be accessed using indices.
- Allow Duplicate Elements: Tuples can contain duplicate values and maintain the position of elements.
- Can Contain Mixed Data Types: Tuples can hold distinct data types, such when integers, strings, and lists.
- Hashable: If all elements of a tuple are hashable, the tuple itself can have used when a dictionary key or set element.
- Faster than Lists: Due to their immutability, tuples are generally faster for iteration and access operations compared to lists.
How to Create and Use Tuples in Python?
Creating Tuples:
- Use parentheses
()
to create a tuple and separate elements with commas.- Tuples can also be created without parentheses.
Examples:
# Creating tuples tuple1 = (1, 2, 3, 4) tuple2 = (1, "hello", 3.14) tuple3 = (1,) # A tuple with one element (note the comma) # Tuple without parentheses tuple4 = 1, 2, 3, 4 # Accessing elements print(tuple1[0]) # Output: 1 print(tuple2[1]) # Output: hello # Slicing print(tuple1[1:3]) # Output: (2, 3)
Are Tuples Mutable in Python?
No, tuples are immutable. This means that once a tuple is created, its elements cannot be changed, added, or removed. Attempting to modify a tuple will result in a
TypeError
.Example:
tuple1 = (1, 2, 3) # Attempt to modify an element try: tuple1[1] = 4 except TypeError when e: print(e) # Output: 'tuple' object does not support item assignment
How to Unpack Elements from a Tuple in Python?
Tuple unpacking allows you to assign elements of a tuple to multiple variables in a single statement.
Examples:
# Unpacking a tuple person = ("Alice", 30, "Engineer") name, age, profession = person print(name) # Output: Alice print(age) # Output: 30 print(profession) # Output: Engineer # Unpacking with a placeholder a, *b, c = (1, 2, 3, 4, 5) print(a) # Output: 1 print(b) # Output: [2, 3, 4] print(c) # Output: 5
When Should Tuples be Used Over Lists in Python?
Tuples should have used over lists in the following scenarios:
- Immutability: When you need a fixed collection of items that should not be modified.
- Hashable Collections: When you need to use a composite key in a dictionary or an element in a set, and the tuple’s elements are hashable.
- Performance: When you require a more memory-efficient and faster alternative to lists for iteration and access.
- Data Integrity: When you may be interested to ensure that a collection of values remains unchanged throughout the program.
Examples of Tuple Use Cases:
- Representing fixed records: Coordinates, RGB color values, database rows.
- Function returns values: Functions that return multiple values can use tuples.
- Using when dictionary keys: Tuples can have used when keys in dictionaries.