
Tuples
Tuples are similar to lists but are immutable, meaning their contents cannot be changed after creation. Tuples are created using parentheses ()
or the tuple()
constructor.
Tuples are widely used in Python due to their performance advantage over lists, especially in situations where a fixed collection of items is needed.
Properties of Tuples
- Immutable: Tuple's elements can't be modified after creation.
- Ordered: Tuples maintain the order of elements.
- Indexable: Elements can be accessed by their index.
- Iterable: Tuples can be used in loops.
- Tuples can contain a mix of data types.
Example
The tuple below contains integers, a string and a boolean value.
# Create a tuple named sample_tuplesample_tuple = (1, 2, 'hello', True)
Indexing and Slicing Tuples
Similar to lists, tuples allow retrieving subsets through indexing or slicing.
Indexing
Indexing involves retrieving a particular element by its index. For instance, to retrieve 'hello' from sample_tuple
, you would use index 2. It's important to note that in Python, as with many programming languages, indexing starts from 0.
# Create a tuple named sample_tuplesample_tuple = (1, 2, 'hello', True)print(sample_tuple)
Output:
(1, 2, 'hello', True)
# Example of accesing the first element of sample_tupleprint(sample_tuple[0])
# Example of accessing the word 'hello' print(sample_tuple[2])
Output:
1
hello
We can also use negative indexing which starts from the end, e.g. sample_tuple[-1]
accesses the last element.
# Access the last element of sample_tupleprint(sample_tuple[-1])
# Access the word 'hello' using negative indexingprint(sample_tuple[-2])
Output:
True
hello
Slicing
Slicing refers to access a subset of a tuple. It's done using the colon :
symbol, e.g. sample_tuple[0:3]
retrieves the first three elements of the tuple. It's inclusive on the left and exclusive on the right.
Syntax: tuple[start : stop : step]
- start: The starting index (inclusive)
- stop: The ending index (exclusive)
- step: The step size (optional).
If the start or stop index is omitted, it defaults to the beginning or end of the tuple, respectively. E.g. sample_tuple[:3]
is equivalent to sample_tuple[0:3]
, and sample_tuple[2:]
is the same as sample_tuple[2:4]
The step parameter specifies intervals, so sample_tuple[::2]
accesses every second element in the list.
Example of slicing a tuple
# Create a new listtuple_new = (10, 20, 30, 40, 50, 60)print('tuple_new: ', tuple_new)
Output:
tuple_new: (10, 20, 30, 40, 50, 60)
# 1. Get elements from index 0 to 2print(tuple_new[0:3])
# 2. Get elements from index 1 to 4print(tuple_new[1:5])
Output:
(10, 20, 30)
(20, 30, 40, 50)
# 3. Get every second element starting from index 0print('Get every second element starting from index 0:')print(tuple_new[::2])
print('---------------------')
# 4. Get every second element starting from index 1print('Get every second element starting from index 1:')print(tuple_new[1::2])
Output:
Get every second element starting from index 0:
(10, 30, 50)
---------------------
Get every second element starting from index 1:
(20, 40, 60)
Methods of Tuples
Tuples have fewer methods compared to lists because they are immutable. Therefore, tuples lack methods for adding, removing, or modifying existing elements. However, they still provide some commonly used methods.
len()
Function
The len()
function returns the number of elements in a tuple.
# Create a new listtuple_sample = (10, 20, 30, 40, 50, 60)
# get the number of elements in the tupleprint('the length of the tuple is', len(tuple_sample))
Output:
the length of the tuple is 6
index()
Function
The index()
function finds the first occurrence of a specified value and returns its index.
Syntax: tuple.index(item)
- item: item is the target value you want to find the index of in the tuple.
# Create a tuplesample_tuple = ['hello', 'world', 'this', 'is', 'my', 'first', 'line', 'of', 'code', 'hello', 'again', 'hello']
# Get the index of word 'first' in the tupleprint('index of word "first" in the tuple: ', sample_tuple.index('first'))
# Get the index of word 'hello' in the tupleprint('index of word "hello" in the tuple: ', sample_tuple.index('hello'))
Output:
index of word "first" in the tuple: 5
index of word "hello" in the tuple: 0
The word "first" is the 6th word in the list, so its index is 5 since list index starts from 0.
Though the word "hello" appears three times in the tuple, the index()
method only returns the index of the first occurrence of the word.
count()
Function
The count()
function returns the number of times a specified value occurs in a tuple.
# Create a tuplesample_tuple = ('hello', 'world', 'this', 'is', 'my', 'first', 'line', 'of', 'code', 'hello', 'again', 'hello')
# Count how many times the word 'hello' appeared in the tuplesample_tuple.count('hello')
Output:
3