Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Python
About Lesson

A tuple is a collection of ordered, immutable elements in Python. Unlike lists, tuples cannot be changed (i.e., you cannot add, remove, or modify elements once the tuple is created). Tuples are often used for storing mixed data, like records, and are generally faster than lists due to their immutability.

Key Features of Tuples:

  • Ordered: The order in which elements are inserted is maintained.
  • Immutable: Once created, the elements cannot be modified.
  • Heterogeneous: Can store elements of different data types (e.g., integers, strings, etc.).
  • Indexed: Each element in a tuple has an index, starting from 0.

Syntax:

Tuples are created by placing elements inside parentheses () and separating them with commas.

Example:

Python
# Creating a tuple
my_tuple = (1, 2, 3, 'hello', True)

# Accessing elements
print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: 'hello'

Nested Tuple

Tuples can contain other tuples.

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

Tuple Unpacking

You can “unpack” the elements of a tuple into separate variables.

Python
my_tuple = (10, 20, 30)
a, b, c = my_tuple
print(a, b, c)  # Output: 10 20 30

Tuple with Different Data Types

Python
mixed_tuple = (42, "hello", 3.14, [1, 2, 3], True)
print(mixed_tuple)  # Output: (42, 'hello', 3.14, [1, 2, 3], True)

Accessing Tuple Elements

Tuples are indexed collections, meaning you can access individual elements using their indices. The index starts from 0 for the first element, and negative indices allow access from the end of the tuple.

Indexing:
Python
my_tuple = (10, 20, 30, 40, 50)

print(my_tuple[0])  # Output: 10
print(my_tuple[4])  # Output: 50

Negative Indexing:

pythonCopy codeprint(my_tuple[-1])  # Output: 50 (last element)
print(my_tuple[-2])  # Output: 40 (second-last element)

Slicing:

Tuples can be sliced using the colon : operator, which creates a sub-tuple from the original tuple.

Python
# Slicing from index 1 to 3 (excluding index 3)
print(my_tuple[1:4])  # Output: (20, 30, 40)

# Slicing from the beginning to index 2 (excluding index 2)
print(my_tuple[:2])   # Output: (10, 20)

# Slicing from index 2 to the end
print(my_tuple[2:])   # Output: (30, 40, 50)