Welcome to our deep dive into Python's Tuple Methods! In this tutorial, we'll explore various methods that help you manipulate and work with tuples effectively. 📝
Before we start, let's briefly revise what a tuple is. A tuple is a collection of ordered, immutable (cannot be changed once created) elements, enclosed within parentheses.
my_tuple = (1, 'apple', 3.14)Tuple methods are functions that operate on tuples, making it easier for us to perform various tasks. Here are the main methods we'll discuss:
len(tuple_name)tuple_name[index]tuple_name.count(element)tuple_name.index(element)tuple_name + tuple_2tuple_name * multiplierlen(tuple_name) 📝The len() function returns the number of elements in a given tuple.
my_tuple = (1, 'apple', 3.14, 'banana')
print(len(my_tuple)) # Output: 4tuple_name[index] 📝Accessing a tuple element involves specifying its index within the tuple. Remember, Python uses zero-based indexing, so the first element has an index of 0.
my_tuple = (1, 'apple', 3.14, 'banana')
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: bananatuple_name.count(element) 📝The count() function tells you how many times a given element appears within the tuple.
my_tuple = (1, 1, 2, 1, 2)
print(my_tuple.count(1)) # Output: 3
print(my_tuple.count(3)) # Output: 0tuple_name.index(element) 📝The index() function returns the index of the first occurrence of a given element within the tuple.
my_tuple = (1, 'apple', 3.14, 'banana', 1)
print(my_tuple.index(1)) # Output: 0 or 4tuple_name + tuple_2 📝Concatenating tuples is as simple as adding them together. This creates a new tuple with all elements from both tuples.
tuple_1 = (1, 'apple')
tuple_2 = (2, 'orange')
result = tuple_1 + tuple_2
print(result) # Output: (1, 'apple', 2, 'orange')tuple_name * multiplier 📝Repeating a tuple multiple times creates a new tuple with the original elements repeated as many times as specified by multiplier.
my_tuple = ('hello',)
print(my_tuple * 3) # Output: ('hello', 'hello', 'hello')Which method returns the number of elements in a tuple?
What does the `index()` method do?