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.
Tuples are created by placing elements inside parentheses.
# Tuple Example fruits = ("apple", "banana", "cherry") print(fruits) # Output: ('apple', 'banana', 'cherry')
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
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
You can find the length of a tuple using the len()
function.
# Tuple Length fruits = ("apple", "banana", "cherry") print(len(fruits)) # Output: 3
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')
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
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')
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')
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!