Tuples are ordered collections of items written inside circular brackets and tuples cannot be changed meaning they are immutable. Below are some features of Python Tuples.
- Ordered Collections of Objects
- Items inside tuple can be accessed using square brackets
- Tuples are immutable, meaning once created these cannot be changed
Let’s deep dive into Python Tuples.
How to create tuple in Python?
Tuples can be created by putting comma separated list of items in circular brackets. These items inside tuple can be of any Data Type like string, list.
# Creating Tuple in Python t = (18, 29, 46)
Tuples can also be created using tuple() function as well.
# Creating Tuples in Python t = tuple(19, 27, 63)
How to create an empty tuple?
An empty tuple can be created by using just empty circular brackets or by calling tuple() function without any parameter.
- () is an empty tuple
- tuple() is also an empty tuple
Accessing Items inside a Python Tuple
Items inside a tuple can be accessed by putting index number inside square brackets after name of tuple. For example – If you have a Python Tuple t = (19, 28, 261) then for accessing element at index position 1, do t.
# Creating a Python Tuple t = (28, 194, 37, 81, 67) t # Returns 28 t # Returns 194 t # Returns 67
Finding length of a Tuple
Simplest approach which exists for finding length of tuple is to use len(tuple name) function.
Syntax : len()
Parameter : tuple
Returns : Length of tuple
# Python code for finding length of a Tuple t = (38, 29, 65, 78, 91, 35, 48) len(t) # Returns 7