How to Create and Use Tuples in Python
In Python, tuples are an important type of data structure. They are similar to lists but have a key distinction – they are immutable, which means that once created, their value cannot be changed. This key feature helps make tuples useful in different programming scenarios. In this article, we’ll explore the basics of creating and using tuples in Python.
Creating a Tuple in Python:
We can create a tuple in Python by assigning values to it, usually separated by commas. Or we can use the tuple() function to create an empty tuple or create a tuple from an existing iterable object like a list or string. Here are some examples:
# Creating a tuple with values in it
tup = (‘apple’, ‘banana’, ‘cherry’)
# Creating an empty tuple
empty_tup = ()
# Converting a list to a tuple
list = [1, 2, 3]
tup = tuple(list)
print(tup) #Output: (1, 2, 3)
Accessing Tuple Elements:
We can access tuple elements by their index number just like we do with lists. Tuples are zero-indexed, which means that their index starts from zero. To access a specific element, we simply use square brackets [ ] and the element’s index number in the tuple. For example:
tup = (‘apple’, ‘banana’, ‘cherry’)
print(tup[1]) #Output: banana
Slicing Tuples:
We can also slice tuples using the colon (:) operator to extract a specific subset of elements from the tuple. For example:
tup = (1, 2, 3, 4, 5)
print(tup[1:4]) #Output: (2, 3, 4)
Concatenating Tuples:
We can concatenate tuples using the + operator. This creates a new tuple containing all the elements from both the operands. For example:
tup1 = (1, 2, 3)
tup2 = (4, 5)
tup3 = tup1 + tup2
print(tup3) #Output: (1, 2, 3, 4, 5)
Using Tuples with Loops:
Tuples can be used in loops as well. The elements of a tuple can be accessed by assigning them to separate variables. In a loop, we can use this feature to iterate over the elements of a tuple. Here’s an example:
tup = (‘apple’, ‘banana’, ‘cherry’)
for x in tup:
print(x)
Output:
apple
banana
cherry
Using Tuples for Multiple Assignment:
Tuples can be used for multiple assignments in Python. This allows us to assign multiple variables using a single tuple. For example:
tup = (‘apple’, ‘banana’, ‘cherry’)
(a, b, c) = tup
print(a) #Output: apple
Using Tuples as Dictionary Keys:
Tuples can be used as dictionary keys in Python. Unlike lists, tuples are immutable and therefore can be used as keys for dictionary mapping. This means that we can use tuples to store key-value pairs in a dictionary. For example:
dict = {(‘apple’, 100): ‘Fruit’, (‘cat’, 500): ‘Animal’}
print(dict) #Output: {(‘apple’, 100): ‘Fruit’, (‘cat’, 500): ‘Animal’}