In this article, we are going to study Python Tuple with examples.
Tuples in Python
A sequence of elements with commas between them is known as Python Tuples. A tuple’s indexing and repetitions are similar to a list, but it is unchangeable, unlike a list that is mutable. the tuple is one of the built-in (pre-defined by the programming language) datatypes in python.
Creating Tuples in Python :
For creating a list we use [], for creating a tuple we will use the () operator.
Python Tuple Example :
Here is an example of tuples in python
tuple = ("T", "for", "TechStudy")
print(tuple)
output: ('T', 'for', 'TechStudy')
Access the values in tuples.
Value in tuple can be accessed using square brackets for slicing and indexing and its value can be obtained as well.
Python tuple methods to access value
Method 1:
Example python tuple value using Positive Index:
tuple = ("T", "for", "TechStudy")
print(tuple)
print("Value in tuple[0] = ", tuple[0])
print("Value in tuple[1] = ", tuple[1])
print("Value in tuple[2] = ", tuple[2])
Output :
(‘T’, ‘for’, ‘TechStudy’)
Value in tuple[0] = T
Value in tuple[1] = for
Value in tuple[2] = TechStudy
Time complexity: O(1).
Auxiliary space: O(1).
Method 2:
Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the second last item and so on.
Example python tuple value using Negative Index:
# accessing the elements of the tuple through negative indexing
vari = ('t', 'e', 'c', 'h', 's', 't', 'u', 'd', 'y')
print(vari[-1])
print(vari[-2])
print(vari[-3])
Output:
y
d
u
Slicing Tuples Python :
Through slicing we can access a tuple of a specific range.
Example :
Example for python slicing tuples:
vari = ('t', 'e', 'c', 'h', 's', 't', 'u', 'd', 'y')
# accessing the tuple elements using the slicing approach in python
# elements 3nd to 4th index
print(vari[2:4])
# printing the elements from the beginning to 2nd
print(vari[:-7]) # prints ('p', 'r')
# printing the elements from index 8th to end
print(vari[7:])
# printing the elements beginning to end
print(vari[:])
Output :
(‘c’, ‘h’)
(‘t’, ‘e’)
(‘d’, ‘y’)
(‘t’, ‘e’, ‘c’, ‘h’, ‘s’, ‘t’, ‘u’, ‘d’, ‘y’)
Python Tuple Length
We can determine the python tuple size through len() method.
Example :
tuple = ("T", "for", "TechStudy")
print(len(tuple))
Output :
3
Tuple with One Item:
We can create tuple with one item but having a comma “,” if comma is missing then it will become a String.
Example:
tuple1 = ("techstudy",)
print(type(tuple1))
tuple2 = ("techstudy")
print(type(tuple2))
Output :
<class ‘tuple’>
<class ‘str’>
Mixed Tuple
A tuple has elements with different datatypes.
Example:
tuple1 = ("tech", 1, True, 2, "study")
print(tuple1)
Output:
(‘tech’, 1, True, 2, ‘study’)