In Python, we often need to work with collections of data. These collections may contain sets of values, which we refer to as pairs.
Working effectively with these pairs often involves performing tasks such as sorting, iterating, and manipulating them.
In Python, pairs can be created by various means, however, the most commonly used method is by using the built-in data type called tuples. Tuples are immutable which means they can’t be modified after they are created.
Step 1: Creating a Pair
Creating pairs in Python can be done using tuples. A tuple is created by placing all the elements, separated by commas, inside parentheses ().
1 2 3 |
# Creating a pair pair = ('apple', 'banana') print(pair) |
This will output the pair:
('apple', 'banana')
Step 2: Accessing Elements in a Pair
You can access elements in a pair much like how you would with a list – using their index. Indexing starts at 0.
1 2 3 |
# Accessing elements in a pair print(pair[0]) print(pair[1]) |
The output would be:
'apple' 'banana'
Step 3: Altering a Pair
As mentioned earlier, tuples are immutable, which means you cannot change an element of a pair once it is assigned. If you try to do so, you will encounter an error. For instance:
1 |
pair[1] = 'orange' |
This would result in a TypeError stating ‘tuple’ object does not support item assignment.
Step 4: Iterating Over a Pair
Just like lists, you can iterate over tuples using a simple for loop.
1 2 3 |
# Iterating over a pair for item in pair: print(item) |
This would output each item in the pair on a new line.
Step 5: Nesting Pairs
Pairs can contain other pairs (or lists), making them nested. You can access elements in nested pairs using their respective indices.
1 2 3 4 |
# Creating a nested pair nested_pair = (('apple', 'banana'), ('grape', 'orange')) print(nested_pair[0][0]) print(nested_pair[1][1]) |
This would output ‘apple’ and ‘orange’, respectively.
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Creating a pair pair = ('apple', 'banana') print(pair) # Accessing elements in a pair print(pair[0]) print(pair[1]) # Iterating over a pair for item in pair: print(item) # Creating a nested pair nested_pair = (('apple', 'banana'), ('grape', 'orange')) print(nested_pair[0][0]) print(nested_pair[1][1]) |
Conclusion
Pairing in Python is a powerful tool and is widely applied in various domains like data analysis and machine learning. They allow us to store data in an ordered, immutable fashion, making them perfect for holding related pieces of data.
The more you work with Python, the more you will have to use and manipulate pairs in your projects. It’s therefore crucial to be comfortable with this fundamental Python concept.