PYTHON Tutorial



TUPLES IN PYTHON


📜 Tuples in Python

A tuple in Python is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning once created, their values cannot be modified. Tuples are defined by enclosing elements inside parentheses, separated by commas.

🔸 Creating a Tuple

Tuples are created by placing elements inside parentheses.

# Tuple Example
fruits = ("apple", "banana", "cherry")
print(fruits)
# Output: ('apple', 'banana', 'cherry')
  

🔸 Accessing Tuple Elements

You can access elements of a tuple using indexing, similar to lists.

# Accessing Tuple Elements
fruits = ("apple", "banana", "cherry")
print(fruits[0])  # Access first element
print(fruits[1])  # Access second element
# Output:
# apple
# banana
  

🔸 Tuple Immutability

Tuples are immutable, so you cannot change, add, or remove elements after the tuple is created.

# Trying to modify a tuple will raise an error
fruits = ("apple", "banana", "cherry")
# fruits[1] = "blueberry"  # This will raise a TypeError
  

🔸 Tuple Length

You can find the length of a tuple using the len() function.

# Tuple Length
fruits = ("apple", "banana", "cherry")
print(len(fruits))
# Output: 3
  

🔸 Nested Tuples

Tuples can contain other tuples, creating a nested structure.

# Nested Tuple
nested_tuple = (("apple", "banana"), ("cherry", "orange"))
print(nested_tuple[0])  # Access the first tuple
# Output: ('apple', 'banana')
  

🔸 Tuple Packing and Unpacking

Tuples can be "packed" by assigning multiple values to a single tuple and "unpacked" by extracting values from the tuple into separate variables.

# Tuple Packing
fruits = ("apple", "banana", "cherry")

# Tuple Unpacking
a, b, c = fruits
print(a)  # Output: apple
print(b)  # Output: banana
print(c)  # Output: cherry
  

🔸 Tuple Concatenation

You can concatenate two tuples using the + operator.

# Tuple Concatenation
fruits = ("apple", "banana")
vegetables = ("carrot", "potato")
combined = fruits + vegetables
print(combined)
# Output: ('apple', 'banana', 'carrot', 'potato')
  

🔸 Tuple Repetition

You can repeat the elements of a tuple using the * operator.

# Tuple Repetition
fruits = ("apple", "banana")
repeated_fruits = fruits * 2
print(repeated_fruits)
# Output: ('apple', 'banana', 'apple', 'banana')
  
💡 Tip: - Tuples are perfect for storing data that should not be modified. - They can be used as keys in dictionaries since they are immutable, unlike lists.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review