No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python Tuples

Python Tuples

In Python, a tuple is a collection of items that is ordered and immutable (unchangeable). Tuples are written with round brackets () and can contain items of different data types.

Key Characteristics of Tuples:

  1. Ordered: The items have a defined order.
  2. Immutable: Once created, the items in a tuple cannot be changed, added, or removed.
  3. Allow Duplicates: Tuples can contain duplicate values.

Example:

# Creating a tuple
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)  # Output: ('apple', 'banana', 'cherry')

# Accessing elements
print(my_tuple[1])  # Output: banana

# Tuples can contain different data types
mixed_tuple = ("apple", 42, True)
print(mixed_tuple)  # Output: ('apple', 42, True)

# Tuples can also be nested
nested_tuple = (my_tuple, mixed_tuple)
print(nested_tuple)  # Output: (('apple', 'banana', 'cherry'), ('apple', 42, True))

Special Cases:

  • Single-item tuple: To create a tuple with one item, include a trailing comma.
single_item_tuple = ("apple",)
print(type(single_item_tuple))  # Output: <class 'tuple'>

Tuples are useful when you want to ensure that the data remains constant throughout the program. 

Leave A Comment

Your email address will not be published. Required fields are marked *