USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Tuples

Lesson 6/15 | Study Time: 25 Min

Tuples in Python



A tuple in Python is an ordered, immutable collection of elements, which means that once a tuple is created, its contents cannot be changed, modified, or deleted individually. Tuples can store multiple types of data together, such as integers, strings, floats, booleans, lists, or even other tuples. Because of their immutability, tuples provide data safety and consistency, ensuring that important information remains constant throughout a program. Tuples are faster and more memory-efficient than lists due to their fixed size. They support indexing, slicing, iteration, and unpacking, and built-in functions like len(), max(), min(), and type(). Tuples are often used when data integrity is critical, such as storing coordinates, configuration settings, or records that should not be altered. Unlike lists, tuples can be used as dictionary keys if they contain only immutable elements, making them valuable for advanced data structures.



1. Creating a Tuple


A tuple in Python is created by placing elements inside parentheses ( ), separated by commas. Tuples can store multiple types of data, such as integers, strings, floats, or even other tuples. If there is only one element, a trailing comma is required to make it a tuple. Tuples can also be empty, which is represented by (). Creating tuples is simple and efficient, making them ideal for storing fixed collections of data.

Syntax:
tuple_name = (item1, item2, item3, ...)

Examples:
my_tuple = (10, 20, 30, "Python", 3.14)
print(my_tuple) # Output: (10, 20, 30, 'Python', 3.14)

single = (

single = (5,)
print(type(single)) # Output: <class 'tuple'>

empty = ()

print(empty) # Output: ()

2. Accessing Tuple Elements (Indexing and Slicing)


Tuple elements can be accessed using indexing, where each element has a position starting from 0. Negative indices allow access from the end of the tuple. Slicing is used to retrieve a portion of the tuple by specifying a start and end index. Tuples support step values in slicing to skip elements as needed. Indexing and slicing make tuples flexible to read and extract data without modifying the original tuple.

Syntax:
tuple_name[index] # Access single element
tuple_name[start:end:step] # Slice elements


Examples:
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry

numbers = (

numbers = (1, 2, 3, 4, 5, 6)
print(numbers[1:4]) # Output: (2, 3, 4)
print(numbers[::2]) # Output: (1, 3, 5)

3. Tuple Immutability


Tuples in Python are immutable, which means their elements cannot be changed, added, or removed after creation. This property ensures data consistency and safety throughout the program. Attempting to modify a tuple element will raise a TypeError. Immutability makes tuples faster and more memory-efficient compared to lists. Because of this, tuples are ideal for storing constant or fixed collections of data that should not be altered.

Example:
t = (1, 2, 3)
# t[0] = 10 # Uncommenting this will cause TypeError


4. Tuple Concatenation and Repetition


Tuples can be joined together using concatenation with the + operator to create a new tuple. Repetition allows a tuple to be repeated multiple times using the * operator. These operations do not modify the original tuples, instead they return a new tuple. Concatenation and repetition make it easy to combine or expand tuples efficiently. They are useful when working with fixed data sequences that need to be reused or extended.


Syntax:

tuple1 + tuple2

Examples:
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # Output: (1, 2, 3, 4)

t = (

t = (5, 6)
print(t * 3) # Output: (5, 6, 5, 6, 5, 6)

5. Nested Tuples


Tuples in Python can contain other tuples or sequences as elements, creating a nested structure. Nested tuples allow you to group related data hierarchically within a single tuple. You can access elements in nested tuples using multiple indices. This structure is useful for storing complex or multi-dimensional data. Nested tuples maintain the immutability and ordered nature of regular tuples while adding flexibility for structured data storage.


Example:
nested = (1, 2, (3, 4))
print(nested[2]) # Output: (3, 4)
print(nested[2][1])

6. Tuple Unpacking


Tuple unpacking allows you to assign each element of a tuple to separate variables in a single statement. The number of variables must match the number of elements in the tuple. This feature makes it easy to extract and use tuple data efficiently. Tuple unpacking improves code readability and reduces the need for indexing. It is commonly used when working with functions that return multiple values or structured data.

Syntax:
var1, var2, var3 = tuple_name


Example:
person = ("Mayank", 21, "Coder")
name, age, profession = person
print(name) # Output: Mayank
print(age) # Output: 21
print(profession) # Output: Coder


7. Built-in Tuple Functions


Python provides several built-in functions that can be used with tuples to retrieve information or perform operations. Functions like len(), max(), min(), sum(), type(), and sorted() allow you to measure, analyze, and manipulate tuple data without modifying the tuple itself. These functions work efficiently because tuples are immutable and memory-friendly. Using built-in functions makes tuple operations simple, readable, and fast. They are essential for common tasks like counting elements, finding maximum/minimum, or sorting.

a) len() – Returns the number of elements
t = (1, 2, 3, 4)
print(len(t)) # Output: 4


b) max() – Returns the largest element
numbers = (10, 20, 30)
print(max(numbers)) # Output: 30


c) min() – Returns the smallest element
print(min(numbers)) # Output: 10


d) sum() – Returns sum of elements (numeric only)
print(sum(numbers)) # Output: 60


e) type() – Returns type of object
print(type(numbers)) # Output: <class 'tuple'>


f) sorted() – Returns a sorted list from the tuple
nums = (3, 1, 4, 2)
print(sorted(nums)) # Output: [1, 2, 3, 4]


8. Tuple Methods


Tuples support only two built-in methods, count() and index(), due to their immutable nature. The count() method returns the number of times a specific value appears in a tuple. The index() method returns the position of the first occurrence of a specified value. These methods allow you to analyze tuple content without changing it. Tuple methods are simple yet useful for checking frequency and locating elements in a tuple.

a) count() Counts occurrences of a value
numbers = (10, 20, 20, 30, 20)
print(numbers.count(20)) # Output: 3


b) index() Returns index of first occurrence of a value
cities = ("Delhi", "Mumbai", "Chennai")
print(cities.index("Mumbai")) # Output: 1

9. Membership Testing


Membership testing allows you to check if a specific element exists in a tuple using the in and not in operators. It returns a Boolean value (True or False) based on the presence of the element. This operation does not modify the tuple and is very fast due to tuple immutability. Membership testing is useful for validating data or performing conditional checks. It helps in writing cleaner and more readable code when working with tuples.

Example:
fruits = ("apple", "banana", "cherry")
print("apple" in fruits) # Output: True
print("grape" not in fruits) # Output: True


10. Iterating through a Tuple


Tuples can be traversed using loops, such as for or while, to access each element sequentially. Iteration allows you to process or analyze tuple elements efficiently without modifying them. Because tuples are immutable, looping over them is fast and memory-efficient. Iterating is commonly used for displaying values, performing calculations, or applying conditions to each element. It makes tuples flexible to use in repetitive tasks while preserving their original data.

Example:
numbers = (1, 2, 3, 4)
for num in numbers:
print(num)

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.