Wednesday 31 July 2024

Python tuple example

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:

 

  1. **Creating a tuple**: `my_tuple` is created with mixed data types.
  2. **Accessing elements**: Individual elements are accessed using their index.
  3. **Slicing a tuple**: A portion of the tuple is accessed using slicing.
  4. **Nested tuples**: Tuples can contain other tuples as elements.
  5. **Unpacking a tuple**: Elements of the tuple are assigned to individual variables.
  6. **Looping through a tuple**: Each element in the tuple is printed using a for loop.
  7. **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/

No comments:

Post a Comment