Python Tuples Tutorial





  • Introduction to Tuples
  • Creating Tuples
  • Accessing Tuple Elements
  • Tuple Slicing
  • Modifying Tuple Elements
  • Modifying Tuple Elements
  • Tuple Unpacking
  • Tuple Comparison
  • Tuple Concatenation and Repetition
  • Deleting Tuples
  • Tuple Methods
  • Packing and Unpacking Tuples
  • Nested Tuples
  • Tuple Comprehension
  • Advantages and Disadvantages of Tuples

Python Tuples

Tuples are immutable sequences of elements, enclosed in parentheses (). They are similar to lists in Python, but unlike lists, tuples cannot be modified after they are created.

Creating Tuples

Tuples can be created using the tuple() function or by simply enclosing comma-separated values in parentheses.


# Creating a tuple using the tuple() function
my_tuple1 = tuple()

# Creating a tuple with values
my_tuple2 = (1, 2, 3, 4, 5)

# Creating a tuple with mixed data types
my_tuple3 = ('apple', 10, 3.14, True)

Accessing Tuple Elements

Tuple elements can be accessed using indexing, similar to lists. Indexing starts from 0.


# Accessing tuple elements
print(my_tuple2[0])  # Output: 1
print(my_tuple2[2])  # Output: 3

Tuple Slicing

Tuples can be sliced to extract a portion of the tuple. Slicing follows the syntax [start:end:step], where start is the starting index, end is the ending index (exclusive), and step is the step size.


# Slicing a tuple
print(my_tuple2[1:4])  # Output: (2, 3, 4)
print(my_tuple2[0:5:2])  # Output: (1, 3, 5)

Modifying Tuple Elements

Tuples are immutable, which means their elements cannot be modified after they are created. However, you can create a new tuple with modified elements.


# Modifying tuple elements
my_tuple4 = my_tuple2 + (6, 7, 8)
print(my_tuple4)  # Output: (1, 2, 3, 4, 5, 6, 7, 8)

Tuple Unpacking

You can unpack a tuple into multiple variables. The number of variables must match the number of elements in the tuple.


# Tuple unpacking
a, b, c = my_tuple2
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

Tuple Methods