Python Tuple

A tuple in Python is a collection of immutable objects, defined by elements separated by commas and enclosed within parentheses. The key distinction between tuples and lists is that tuples cannot be modified after creation, leading to faster tuple manipulation due to their immutability. This immutability also allows tuples to be used as dictionary keys, unlike lists. Additionally, tuples are often utilized when returning multiple results from a function, providing a convenient way to bundle and transmit multiple values.

Creating a Tuple

A tuple is defined using parentheses (). It is a collection of immutable objects separated by commas and enclosed within the parentheses. To create an empty tuple, you simply use an empty pair of parentheses.

example
a_tuple = () #empty tuple print(a_tuple)
output
()

Creating Tuple with values

example
a_tuple = ('East','West','North','South') print(a_tuple)
output
('East', 'West', 'North', 'South')

Python Tuple with mixed datatypes

example
a_tuple = (1,2,'sunday','monday',3.14) print(a_tuple)
output
(1, 2, 'sunday', 'monday', 3.14)
example
a_tuple = ('1899-10-34', ['Drama', 'Tale of Two Cities']) print(a_tuple)
output
('1899-10-34', ['Drama', 'Tale of Two Cities'])

Accessing tuple values

To access specific elements within a data structure, such as a list or a tuple, we utilize square brackets [], employing a zero-based index to identify the position of the desired element. By employing the indexing mechanism, we can retrieve or manipulate individual items within the data structure, enabling precise data retrieval and modification. The zero-based indexing convention, fundamental in Python, designates the first element as index 0, the second as index 1, and so forth, offering a systematic and consistent approach to access elements within the data structure.

example
a_tuple = (1,2,'sunday','monday',3.14) print(a_tuple[0]) # print 1st element print(a_tuple[1]) # print 2nd element print(a_tuple[-1]) # print last element print(a_tuple[-2]) # print 2nd last element
output
1 2 3.14 monday

Adding Tuple

example
a_tuple = ('1899-10-34', ['Drama', 'Tale of Two Cities']) print(a_tuple) print(a_tuple[0]) # print 1st element print(a_tuple[1]) # print 2nd element
output
('1899-10-34', ['Drama', 'Tale of Two Cities']) 1899-10-34 ['Drama', 'Tale of Two Cities']

Loops and Tuple

example
a_tuple = ('East','West','North','South') for dir in a_tuple: print (dir)
output
East West North South

Tuple print with index number

example
a_tuple = ('East','West','North','South') for i,dir in enumerate(a_tuple): print (i, " " , dir)
output
0 East 1 West 2 North 3 South

Concatenation of Tuples

You can add two or more Tuples by using the concatenation operator "+".

example
a_tuple = ('East','West','North','South') b_tuple = (1,2,3,4,5) c_tuple = a_tuple + b_tuple print(c_tuple)
output
('East', 'West', 'North', 'South', 1, 2, 3, 4, 5)

Tuple length

The function len returns the length of a Tuple, which is equal to the number of its elements.

example
a_tuple = ('East','West','North','South') i = len(a_tuple) print(i)
output
4

Slicing Python Tuples

Python slice extracts elements, based on a start and stop.

example
a_tuple = ('East','West','North','South') slc = a_tuple[1:3] print(slc)
output
('West', 'North')

str[1:3] - The 1 means to start at second element in the Tuples (note that the slicing index starts at 0). The 3 means to end at the fourth element in the list, but not include it. The colon in the middle is how Python's Tuples recognize that we want to use slicing to get objects in the list.

example
a_tuple = ('East','West','North','South') slc = a_tuple[:2] # slice first two elements print(slc)
output
('East', 'West')
example
a_tuple = ('East','West','North','South') slc = a_tuple[2:] # slice from 3rd element, Python starts its index at 0 rather than 1. print(slc)
output
('North', 'South')

Delete Tuple Elements

How to Tuple in Python

Tuples are immutable data structures, which means that once a tuple is created, you cannot change the elements contained within it. The elements of a tuple are fixed and cannot be added, modified, or removed after the tuple is created. This immutability distinguishes tuples from lists, which are mutable and allow modifications.

If you want to remove an entire tuple, you can use the del statement followed by the tuple name. This will completely delete the tuple from memory, freeing up the resources it

example
a_tuple = ('East','West','North','South') del a_tuple print(a_tuple)
output
Traceback (most recent call last): File "sample.py", line 8, in < module > print(a_tuple) NameError: name 'a_tuple' is not defined

Updating a Tuple

While tuples are immutable in Python, it's essential to understand that the immutability applies only to the tuple itself, not its elements. If a tuple contains mutable data types, such as lists, the nested items within those mutable data types can be changed even though the tuple remains immutable.

In other words, you cannot add, remove, or modify the elements of a tuple directly, but if an element within the tuple is a mutable data type (like a list), you can modify its contents.

example
a_tuple = (1,2,3,4,[5,6]) a_tuple[4][1]=12 print(a_tuple)
output
(1, 2, 3, 4, [5, 12])

Tuples as return multiple values

Functions are generally designed to return a single value. However, by using tuples, you can effectively bundle together multiple values into a single entity and return them together from a function.

Tuples offer a convenient way to group multiple values and return them as a single compound value. This is particularly useful when a function needs to output or return multiple pieces of related information, such as multiple results from a calculation or multiple pieces of data extracted from a dataset.

example
def multi(): a=100 b=200 return (a,b) x,y = multi() print(x) print(y)
output
100 200

Nesting of Tuples

example
a_tuple = (1,2,3,4,5) b_tuple = ('a','b','c','d','3') c_tuple = (a_tuple,b_tuple) print(c_tuple)
output
((1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', '3'))

Converting list to a Tuple

You can convert a List to a Tuple by using tuple()

example
a_list = [1,2,3,4,5] a_tuple = tuple(a_list) print(a_tuple)
output
(1, 2, 3, 4, 5)

Repetition in Tuples

Using the * operator repeats a list a given number of times.

example
a_tuple = ('halo','world') a_tuple = a_tuple * 2 print(a_tuple)
output
('halo', 'world', 'halo', 'world')

Tuple repetition Count

Tuple.count(x) return the number of times x appears in the Tuple.

example
a_tuple = ('h','e','l','l','o') cnt=a_tuple.count('l') print(cnt)
output
2

zip() function

The zip() function is used to combine two or more sequences, such as lists or tuples, into a single iterable of tuples. Each tuple contains elements from corresponding positions of the input sequences. This is particularly useful when you want to loop over multiple sequences simultaneously and process their elements together.

example
a_tuple = (1,2,3,4,5) b_tuple = ('a','b','c','d','e') for num, alp in zip(a_tuple,b_tuple): print(num, alp)
output
1 a 2 b 3 c 4 d 5 e

Tuple min(), max()

The min() returns the minimum value from a tuple and max() returns the maximum value from the tuple.

example
a_tuple = (1,2,3,4,5) print(min(a_tuple)) print(max(a_tuple))
output
1 5

Tuple Packing and Unpacking

Packing of tuples refers to the process of creating a tuple by comma-separating multiple items within parentheses (). The items enclosed within the parentheses are automatically packed together to form a single tuple. For example:


Python Tuple Packing and Unpacking

Conclusion

A tuple is an immutable collection of objects, defined by elements separated by commas and enclosed within parentheses (). Once a tuple is created, its elements cannot be modified, making tuples suitable for representing fixed data or information that should remain constant throughout the program's execution. Tuples are useful for efficient data storage, as dictionary keys, and when returning multiple results from a function, due to their immutability and ability to hold multiple values in a structured manner.