Python Tuples
⏱ Estimated reading time: 2 min
Python Tuples
A tuple in Python is an ordered collection of items, similar to a list, but tuples are immutable, meaning their elements cannot be changed after creation. Tuples can contain elements of different data types.
Creating a tuple:
Example:
my_tuple = (1, 2, 3, 4)
fruits = ("apple", "banana", "cherry")
mixed = (1, "apple", 3.5)
Single-element tuple:
To create a tuple with one item, include a comma.
Example:
single = (5,)
print(type(single)) #
Accessing elements:
Use indexing to access items. Indexing starts from 0.
Example:
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
Slicing a tuple:
Get a sub-tuple using a range of indexes.
Example:
print(fruits[0:2]) # ('apple', 'banana')
print(fruits[1:]) # ('banana', 'cherry')
Immutability of tuples:
You cannot change, add, or remove elements.
Example:
fruits[1] = "blueberry" # Error
Tuple concatenation:
You can combine tuples using +.
Example:
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3) # (1, 2, 3, 4)
Repetition:
You can repeat tuples using *.
Example:
t = (1, 2)
print(t * 3) # (1, 2, 1, 2, 1, 2)
Iterating through a tuple:
Use a for loop to access each element.
Example:
for fruit in fruits:
print(fruit)
Checking existence of an element:
Use in to check if an item exists.
Example:
if "apple" in fruits:
print("Found")
Tuple methods:
Tuples have only two built-in methods:
-
count(): returns the number of times a value occurs
-
index(): returns the index of the first occurrence of a value
Example:
numbers = (1, 2, 2, 3)
print(numbers.count(2)) # 2
print(numbers.index(3)) # 3
Nested tuples:
Tuples can contain other tuples.
Example:
nested = ((1,2), (3,4))
print(nested[1][0]) # 3
Register Now
Share this Post
← Back to Tutorials