Skip to Content
Course content

A tuple in Python is an immutable sequence of elements, which can hold items of any data type (e.g., numbers, strings, other tuples, etc.). Unlike lists, tuples cannot be changed once they are created, which makes them suitable for storing data that should not be modified.

1. Creating Tuples

Tuples are created by placing elements inside parentheses (), with each item separated by commas.

Basic Syntax:

tuple_name = (item1, item2, item3, ...)
  • Empty Tuple: A tuple with no elements.
    empty_tuple = ()
    
  • Single Element Tuple: To create a tuple with one item, a trailing comma is required.
    single_element_tuple = (5,)
    

Example:

# Tuple with multiple data types
my_tuple = (1, "hello", 3.14, True)

2. Accessing Tuple Elements

You can access elements of a tuple using indexing. Like lists, Python uses zero-based indexing for tuples.

Accessing Elements Using Indexing:

my_tuple = (1, "hello", 3.14, True)

# Accessing the first element
print(my_tuple[0])  # Output: 1

# Accessing the second element
print(my_tuple[1])  # Output: hello

# Accessing the last element using negative index
print(my_tuple[-1])  # Output: True

3. Slicing Tuples

Slicing allows you to access a subset of the tuple, just like slicing lists. It uses the syntax tuple[start:end].

  • Start Index: The index from where the slice starts (inclusive).
  • End Index: The index where the slice ends (exclusive).

Example of Slicing:

my_tuple = (1, "hello", 3.14, True, "world")

# Extracting a portion from index 1 to 3 (exclusive)
print(my_tuple[1:4])  # Output: ('hello', 3.14, True)

# Omitting the start index to get a sublist from the beginning
print(my_tuple[:2])  # Output: (1, 'hello')

# Omitting the end index to get a sublist till the end
print(my_tuple[2:])  # Output: (3.14, True, 'world')

# Reversing the tuple using slicing
print(my_tuple[::-1])  # Output: ('world', True, 3.14, 'hello', 1)

4. Modifying Tuples

Unlike lists, tuples are immutable, meaning you cannot change the values of a tuple once it has been created. Any operation that tries to modify a tuple (e.g., assigning to an index) will result in an error.

Example of Attempted Modification (Will Raise Error):

my_tuple = (1, 2, 3)

# Attempt to change the second element (will raise an error)
my_tuple[1] = 4  # TypeError: 'tuple' object does not support item assignment

Although you cannot modify the tuple directly, you can create new tuples by concatenating or slicing existing ones.

Example of Creating a New Tuple:

my_tuple = (1, 2, 3)
new_tuple = my_tuple + (4, 5)  # Concatenate tuples
print(new_tuple)  # Output: (1, 2, 3, 4, 5)

5. Tuple Packing and Unpacking

  • Packing: The process of assigning multiple values to a tuple.
    packed_tuple = 1, "apple", 3.14
    print(packed_tuple)  # Output: (1, 'apple', 3.14)
    
  • Unpacking: The process of breaking a tuple into individual elements.
    my_tuple = (1, "hello", 3.14)
    
    # Unpacking the tuple into variables
    a, b, c = my_tuple
    print(a)  # Output: 1
    print(b)  # Output: hello
    print(c)  # Output: 3.14
    

6. Tuple Methods

Although tuples are immutable, there are still a few built-in methods you can use to interact with them:

  • count(): Returns the number of occurrences of an item in the tuple.
    my_tuple = (1, 2, 2, 3, 2, 4)
    print(my_tuple.count(2))  # Output: 3
    
  • index(): Returns the index of the first occurrence of an item in the tuple.
    my_tuple = (1, 2, 3, 4, 5)
    print(my_tuple.index(3))  # Output: 2
    

7. Nested Tuples

Tuples can contain other tuples, which makes them suitable for representing more complex data structures.

Example of Nested Tuple:

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

8. Tuple vs List

Feature Tuple List
Mutability Immutable Mutable
Syntax Parentheses () Square brackets []
Performance Faster due to immutability Slightly slower due to mutability
Use Case Used for fixed data that should not change Used for data that can change or be modified

Summary of Operations:

  1. Creating Tuples: Use parentheses () to create a tuple.
  2. Accessing Elements: Use zero-based indexing, or negative indexing for elements from the end.
  3. Slicing: Extract a portion of the tuple using the slice notation [start:end].
  4. Modifying Tuples: Tuples are immutable, so modification is not possible directly. You can create new tuples by concatenation.
  5. Packing and Unpacking: Easily assign multiple values to a tuple (packing) or break a tuple into individual variables (unpacking).
  6. Methods: The count() and index() methods are available to interact with tuples.

Understanding tuples and their properties is crucial for efficiently managing data in Python, especially when you need a sequence that should remain constant.

Commenting is not enabled on this course.