Blog
Python tuple example
- July 31, 2024
- Posted by: Riddhi Dhandha
- Category: C Programming Langauge at TCCI C++ Programming Langauge at TCCI Programming Langauges Python Coaching at TCCI
A Python tuple is an immutable sequence type, meaning that once it is created, it cannot be modified. Here’s a basic example to illustrate how to create and use tuples in Python:
“`python
# Creating a tuple
my_tuple = (1, 2, 3, “apple”, “banana”)
# Accessing elements in a tuple
first_element = my_tuple[0] # 1
second_element = my tuple[1] # 2
# Slicing a tuple
sub_tuple = my_tuple[1:3] # (2, 3)
# Tuples can be nested
nested_tuple = (1, 2, (3, 4, 5))
# Unpacking a tuple
a, b, c, d, e = my_tuple
# Looping through a tuple
for item in my_tuple:
print(item)
# Trying to modify a tuple (this will raise an error)
# my_tuple[0] = 10 # TypeError: ‘tuple’ object does not support item assignment
“`
Here’s what happens in each part of the example:
- **Creating a tuple**: `my_tuple` is created with mixed data types.
- **Accessing elements**: Individual elements are accessed using their index.
- **Slicing a tuple**: A portion of the tuple is accessed using slicing.
- **Nested tuples**: Tuples can contain other tuples as elements.
- **Unpacking a tuple**: Elements of the tuple are assigned to individual variables.
- **Looping through a tuple**: Each element in the tuple is printed using a for loop.
- **Immutability**: Attempting to change an element of the tuple results in a `Type Error` because tuples are immutable.
TCCI Computer classes provide the best training in all computer courses online and offline through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.
For More Information:
Call us @ +91 98256 18292
Visit us @ http://tccicomputercoaching.com/