Using Tuples Data Structure In Python πŸ˜‹

In this article, we will briefly discuss using Tuples data structure and how it will be different from lists.

Tuples are data structures that are similar to list in every aspect except the way that they are declared, and how much they allow themselves to be modified. A tuple, once created, cannot be modified, like a list can.

When you are storing important information in a list and using it in some other place in your code, you run the risk of accidentally modifying the list or losing the data, because lists can be changed. In this case, tuples will help you to remedy this problem.

Creating an Empty Tuple

A tuple is created by placing all the item inside parentheses () separated by commas.

initial_tuple = ( )
print(initial_tuple)

Output  ( )

Creating a Populated Tuple

first_tuple = ("Python", 39, "Baker Street", 9.8)

Accessing Tuple Element 

Indexing 

To access the element from the tuple we need to use the index number. The index must be an integer. Let's see a few examples:

Let's suppose a tuple with 10 elements has indices from 0 to 9. Whenever we try to access an index outside of the tuple range like 10,11,.... in this example, we will get an Index Error.

# Accessing tuple elements using indexing
my_tuple = ('q','w','e','r','t','y')

#Output

print(my_tuple[0]) Β  # 'q'Β 
print(my_tuple[5]) Β  # 'y'Β 
# nested tuple
nested_tuple = ("mice", [8, 5, 6], (0, 2, 5))

# nested index
print(n_tuple[0][1])       # 'i'
print(n_tuple[1][1])       # 5

Negative Indexing

A tuple also allows negative indexing. We already know that index -1 refers to the last item, -2 to the second last item, and so on. 

# Negative indexing for accessing tuple elements
my_tuple = ('p', 's', 'm', 'n', 'q', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

Deleting a Tuple

As we learned in the beginning of this article, we cannot change the elements in a tuple. This means that we cannot delete or remove items from a tuple.

But deleting a tuple entirely is possible by using del keyword.

# Deleting tuples
new_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# Can delete an entire tuple
del new_tuple

# NameError: name 'my_tuple' is not defined
print(my_tuple)

Tuple is deletedΒ 

Happy Learning!  :) 


Similar Articles