Tuples
A tuple is an ordered, immutable collection of elements. This means once a tuple is created, you cannot add, remove, or change its elements. Tuples are defined using parentheses () and can store a variety of data types.
Creating Tuples
Section titled “Creating Tuples”You create a tuple by enclosing its elements in parentheses and separating them with commas.
my_tuple = (1, 2, 3, 'hello')print(my_tuple) # Output: (1, 2, 3, 'hello')Empty Tuples To create an empty tuple, simply use an empty pair of parentheses.
empty_tuple = ()print(empty_tuple, type(empty_tuple)) # Output: () <class 'tuple'>Single-Value Tuples A tuple with only one element must include a trailing comma after the value. Without the comma, Python treats it as a regular value inside parentheses, not a tuple.
single_tuple = (5,)print(single_tuple) # Output: (5,)Accessing Tuple Elements
Section titled “Accessing Tuple Elements”Like lists, tuples are indexed, with the first element at index 0. You can use square brackets [] to access individual elements. Tuples support both positive and negative indexing.
Positive Indexing
Positive indexing starts from 0 and goes up.
my_tuple = ('apple', 'banana', 'cherry')print(my_tuple[1]) # Output: bananaNegative Indexing
Negative indexing starts from -1 and works backward from the end of the tuple.
my_tuple = ('apple', 'banana', 'cherry')print(my_tuple[-1]) # Output: cherrySlicing
Slicing allows you to extract a range of elements from a tuple, which creates a new tuple. The syntax is [start:end], where the end index is exclusive.
my_tuple = (10, 20, 30, 40, 50)print(my_tuple[1:4]) # Output: (20, 30, 40)Tuple Methods
Section titled “Tuple Methods”While tuples are immutable, Python provides a few built-in methods for working with them.
-
count()Thecount()method returns the number of times a specific value appears in a tuple.my_tuple = (10, 20, 30, 20, 40, 20)occurrences = my_tuple.count(20)print(occurrences) # Output: 3 -
index()Theindex()method finds the first occurrence of a specified value and returns its index. It raises aValueErrorif the value is not found.my_tuple = (10, 20, 30, 40, 50)position = my_tuple.index(30)print(position) # Output: 2You can also provide optional
startandendarguments to search within a specific slice of the tuple.my_tuple = (10, 20, 30, 40, 50, 30)position = my_tuple.index(30, 3)print(position) # Output: 5