Tuple in Python

Tuples in Python are a built-in data type for storing multiple items in a single variable. They are a collection of objects that are ordered and immutable. Tuples are essentially immutable sequences that can hold a mix of any Python objects or data types including numbers, strings, lists, etc.

In Python, tuples are created by placing a sequence of values separated by commas within parentheses().

# Creating a tuple
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

The above code snippet creates a new tuple named my_tuple that contains three string objects. When you run this script, it will print out: ("apple", "banana", "cherry")

Difference between Tuple and List:

While both tuples and lists are used for similar purposes – to store multiple items in a single variable – there are some important differences between them.

  • The major difference lies in their mutability. Lists are mutable, which means you can change their values, size, and can also perform operations like insertion and deletion. On the contrary, tuples are immutable which means once a tuple is created you cannot change its values.
  • Tuples can be used as keys in dictionaries or as elements of a set, whereas lists cannot.
  • Tuples have a smaller memory compared to lists, making them somewhat faster, depending on the operation conducted.

Here’s a side by side comparison:

# Creating a list
my_list = ["apple", "banana", "cherry"]
print(my_list)

# Creating a tuple
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

Why use Tuple in Python:

Although tuples are less popular and less used than lists in Python, they are a fundamental data type that any Python programmer should know. Tuples are commonly used in the following situations:

  • Tuples are commonly used for small collections of values that will not need to change, such as an IP address and port.
  • Since tuples are immutable, they can be used as keys in dictionaries and can be included in sets, whereas lists cannot.
  • Tuples are also used for simultaneous data assignments, packing and unpacking.

Here’s an example of simultaneous data assignment that’s possible because of tuples:

# (age, country, knows_python)
survey = (27, "Vietnam", True)

age = survey[0]
country = survey[1]
knows_python = survey[2]

print(f"Age = {age}")
print(f"Country = {country}")
print(f"Knows Python = {knows_python}")

This code unpacks the survey tuple into multiple variables. This is extremely useful when looping through lists of tuples in Python.

Syntax

A Tuple is an integral data structure of Python, it is an immutable, ordered sequence of elements. To create a tuple, elements should be enclosed in parentheses (()), with each element separated by a comma.

my_tuple = (element1, element2, element3, ..., elementN)

For example:

# Creating a tuple with different type of elements
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

In the above example, we’ve created a tuple my_tuple with an integer, a string, and a float as its elements. Upon printing this tuple, the output would be (1, 'Hello', 3.4)

Creating a Tuple with One Element

Creating a tuple with one element might seem a bit tricky. A single element in parentheses can be misconstrued as a mere element within parentheses for the Python interpreter. For example:

my_tuple = ("hello")
print(type(my_tuple))  # Will output 'str' 

To create a tuple with one element, we need to add a trailing comma after the element. For example:

my_tuple = ("hello",)
print(type(my_tuple))  # This will now output 'tuple'

Creating a Tuple Without Using Parentheses

Python allows us to create a tuple without the use of parentheses. This is known as Tuple Packing.

# Creating a tuple without parentheses
my_tuple = "John", "Peter", "Vicky"
print(my_tuple)  # Outputs: ('John', 'Peter', 'Vicky')
print(type(my_tuple))  # Outputs: 'tuple'

In the above example, we have created a tuple without using parentheses, and when we print the tuple and it’s type we can see we have indeed created a tuple. This further demonstrates the flexibility of Python as a programming language. However, it is still a good practice to encase the elements in parentheses in order to avoid any confusing situations regarding operator precedence.

Accessing Elements in a Tuple

In Python, tuples are immutable sequences of arbitrary elements. Owing to their immutable nature, you cannot add or remove items from a tuple, but you can access and retrieve its elements in several ways. Let’s learn how to access elements in a tuple.

Accessing a Single Element

The simplest method to access an item in a tuple is by using an index. In Python, indices start from zero. Hence, the index of the first element is 0, the second element is 1, and so forth. To access an element, you use the tuple name followed by square brackets [ ] within which you specify the index of the desired item.

Consider a tuple called my_tuple with the following elements:

my_tuple = ("apple", "banana", "cherry", "dates")

Let’s say you want to access the second element banana. You would do so as follows:

print(my_tuple[1])

Result: banana

Slicing a Tuple

You can access a range of items in a tuple by using a slice. A slice is defined by specifying the start and end indices separated by a colon : inside the square brackets[]. The start index is inclusive, while the end index is not.

Let’s say you want to access the second and third items of the my_tuple. You would do so as follows:

print(my_tuple[1:3])

Result: (‘banana’, ‘cherry’)

Negative Index in Tuple

Python also supports the use of negative indexing, which allows you to access elements starting from the end of the sequence. -1 represents the last item, -2 is the second last, and so on.

Let’s say you want to access the last element dates from my_tuple. You would do so as follows:

print(my_tuple[-1])

Result: dates

Similarly, slicing can also be performed with negative indices to access a range of items from the end of the tuple. For instance, if you want to access all items from the third last to the end, you can do:

print(my_tuple[-3:])

Result: (‘banana’, ‘cherry’, ‘dates’)

These flexibility in accessing elements make tuples a very handy and efficient data structure in Python. Despite their immutability, tuples can handle an extensive range of operations that can be easily manipulated according to the developers’ requirements.

Immutability of Tuples

In Python, a tuple is defined by a collection of arbitrary objects, separated by commas, and enclosed within parentheses. The distinguishing feature that differentiates tuple from other sequences, like lists, is its immutability.

For instance, consider the following simple tuple:

t = (1, 2, 3)

If you tried to change an element in this tuple, say you want to change the 2 to a 5 such that your expected output is (1, 5, 3), you will encounter a TypeError.

For example:

t[1] = 5
# Output: TypeError: 'tuple' object does not support item assignment

The TypeError is Python’s way of saying that you can’t change a tuple once it has been created. Immutability is useful when you want to enforce write-protection of the data, maintaining the integrity and reliability of the data.

Workarounds to Change a Tuple

Despite the rigidity of tuples, there are still ways to perform changes on them indirectly. These workarounds allow us to mimic tuple change, maintaining the essence of their use while working our way around their immutability.

Conversion to a List

The most straightforward option to alter a tuple would be to convert it into a mutable data structure, perform the necessary changes, then convert it back to a tuple. For example:

t = (1, 2, 3)
# Convert tuple t to a list
l = list(t)
# Now this is a list, we can change its elements
l[1] = 5
# Now convert it back into a tuple
t = tuple(l)

# Print the new tuple
print(t)
# Output: (1, 5, 3)

Concatenation of Tuples

Another viable workaround is called Tuple Concatenation. Since tuples are immutable, appending or merging tuples essentially creates a new one. For example:

t1 = (1, 2, 3)
t2 = (4, 5, 6)

# Concatenate t1 and t2
t3 = t1 + t2

print(t3)
# Output: (1, 2, 3, 4, 5, 6)

It’s important to remember that these workarounds allow us to modify tuples, but they basically create new tuples in the process, maintaining the inherent immutability of the original tuple.

Count() Method

The count() method is used to count the number of times a specified element appears in a tuple. This method can be handy when you need to count the occurrence of a particular element in a tuple.

Here is the syntax for the count() method:

tuple.count(element)

The count() method takes one argument: the element to be counted for its occurrence.

For example, let’s define a tuple and count the occurrence of a specific element:

num_tuple = (1, 2, 3, 2, 4, 2, 5)

# Count the occurrence of `2`
count = num_tuple.count(2)

print(f"The number 2 occurs {count} times.")

In this script, we have a tuple named num_tuple, and we count the occurrence of number ‘2’ in the tuple. When you run the script, the output will be:

The number 2 occurs 3 times.

Index() Method

The index() method is used to find the index of the first occurrence of a specified element in a tuple. This method is useful when you need to know the position of a specific element.

The index() method takes one argument: the element of which you want to find the first occurrence. Syntax for the index() method:

tuple.index(element)

For example, let’s define a tuple and find the index of a specific element:

num_tuple = (1, 2, 3, 2, 4, 2, 5)

# Find the index of `2`
index = num_tuple.index(2)

print(f"The number 2 first occurs at index {index}.")

In this script, we have a tuple named num_tuple, and we find the index of the first occurrence of number 2 in the tuple. When you run the script, the output will be:

The number 2 first occurs at index 1.

Python uses zero-based indexing, i.e., it starts counting from 0. Therefore in the above tuple, the index of the first item (number 1) is 0, and so on.

Tuple operations

Tuple operations like Concatenation, Repetition, Membership, and Iteration, allow us to manipulate and manage the data present in tuples effectively.

  • Tuple Concatenation

Concatenation, essentially, is the operation of joining two or more tuples. A + operator is used between the tuples to concatenate them.

tuple1 = ("Hello", "Tuple")
tuple2 = ("Python", "Tutorial")
tuple3 = tuple1 + tuple2

print(tuple3)

#Output: ('Hello', 'Tuple', 'Python', 'Tutorial')

In the above example, both tuple1 and tuple2 are combined using a Concatenation operator, and the result is saved in tuple3.

  • Tuple Repetition

The repetition operation involves repeating a tuple for a specified number of times. Python uses an * operator for repetition.

#example
tuple1 = ("Python", "Tuple")
tuple2 = tuple1 * 3

print(tuple2)

#Output: ('Python', 'Tuple', 'Python', 'Tuple', 'Python', 'Tuple')

Here, tuple1 is repeated three times to generate tuple2.

  • Tuple Membership

Membership allows us to check if a particular element exists within a tuple or not. Python provides ‘in’ and ‘not in’ operators to carry out this task.

tuple1 = ("Python", "Tuple", "Hello", "World")

print("Python" in tuple1) #checks if Python is a member of tuple1

print("Python" not in tuple1) #checks if Python is not a member of tuple1

#Output:
#True
#False

The output True confirms that Python exists in tuple1. False verifies that Python is indeed a member of tuple1.

  • Tuple Iteration

Iteration allows us to go through each element in a tuple. In Python, we use a for loop to iterate over a tuple.

tuple1 = ("Python", "Tuple", "Hello", "World")

for item in tuple1:
       print(item)

#Output:
#Python
#Tuple
#Hello
#World

In this example, Python iterates over each item in tuple1 and prints it.

Deleting a Tuple:

Tuples are immutable, which means you cannot delete or remove items from it. However, you can totally delete the tuple itself using the del keyword.

del my_tuple

If you try to access the tuple after it’s deleted, you will get an error because the tuple no longer exists.

Differences in Deleting a Tuple and a List:

Unlike tuples, lists in Python are mutable – meaning you can modify them after they are created, including adding and removing items. This fundamental difference makes the process of deleting items from a list different from deleting a tuple.

Here is an example of removing an item from a list:

my_list = ['apple', 'banana', 'pear']
my_list.remove('banana')

print(my_list)  # Output: ['apple', 'pear']

You can even entirely delete a list, just like a tuple, using the del keyword.

del my_list
print(my_list)  # Raises NameError: name 'my_list' is not defined

Python doesn’t support deleting items from a tuple outright, we get around this by slicing and concatenating tuples to remove the specific elements we don’t need.

Techniques to delete a Tuple:

As we cannot delete items from a tuple directly, one way to get around this is by:

  1. converting the tuple to a list
  2. deleting the desired item from the list
  3. then converting the list back to a tuple

For example:

# Start with the original tuple
my_tuple = ('apple', 'banana', 'pear')

# Convert the tuple into a list
list_from_tuple = list(my_tuple)

# Remove the item from the list
list_from_tuple.remove('banana')

# Convert the list back into a tuple
my_new_tuple = tuple(list_from_tuple)

print(my_new_tuple)  # Output: ('apple', 'pear')

That’s to say, if you have a tuple and you want to delete elements from it, you must recreate the tuple without the items you want to delete.

Advantages of Tuple over List

Tuples, in Python, is an ordered collection of elements enclosed in parentheses (). They work almost the same as lists in Python, the only fundamental difference being that lists are mutable while tuples are immutable. This difference leads to a set of advantages of using tuples over lists, like memory usage, safety, applications in dictionary and tuple assignment, packing, and unpacking.

Memory Usage

Tuples consume less memory compared to lists. As a result, tuples are more efficient in terms of memory usage if you have a large amount of data that does not need to be changed over time.

We can utilize sys module in Python to observe the memory consumption:

import sys
list_test = [1, 2, 3, "a", "b", "c", True, 3.14159]
tuple_test = (1, 2, 3, "a", "b", "c", True, 3.14159)
print("List size:", sys.getsizeof(list_test))
print("Tuple size:", sys.getsizeof(tuple_test))

The output is of the above code is:

List size: 128
Tuple size: 112

Lists take a significantly more memory compared to tuples. This difference adds up when dealing with huge amount of data.

Safe to Use

As tuples are immutable, they are safer to use. The data stored in a tuple cannot be altered by mistake or due to some erroneous code.

In the example below, the list data was altered; whereas attempting to alter the data of a tuple resulted in an error.

list_test = [1, 2, 3]
list_test[2] = "Oops."
print(list_test)  # Output: [1, 2, 'Oops.']

tuple_test = (1, 2, 3)
tuple_test[2] = "Oops."  # Output: TypeError: 'tuple' object does not support item assignment

Can Be Used As Dictionary Key

Tuples can be used as keys in a dictionary, which cannot be done with lists as they are mutable and hence un-hashable.

dict_test = {(1, 2, 3): "a", (4, 5, 6): "b"}
print(dict_test[(1, 2, 3)])
# output: 'a'

Tuple Assignment, Packing, and Unpacking

Python supports a feature called tuple assignment, which enables swapping of values without the need for a temporary variable.

a = 5
b = 10
(a, b) = (b, a)
print(a, b)  # Output: 10 5

Additionally, Python also supports:

  • Packing: assign multiple values to a tuple in a single statement.
  • Unpacking : extract multiple, packed values into single variables.
# packing
tuple_test = 1, "a", True, 2.0

# unpacking
a, b, c, d = tuple_test
print(a, b, c, d)  # Output: 1 a True 2.0

Real-world Applications of Tuple

Tuples are extensively utilized in a variety of real-world applications. Here are a few:

  • Database Programming: Tuples are commonly used in database operations because they are immutable and hash-able. They can be used as keys in database operations, which isn’t possible with mutable structures.
employee_database = {(123, "John"):1800000, (124, "Doe"):1200000}
  • Returning Multiple Values: Functions in Python can use tuples to return multiple values.
def min_max(numbers):
return min(numbers), max(numbers)

numbers = [3, 1, 66, 33, 22, 11]
min_val, max_val = min_max(numbers)
  • String Formatting: Tuples assist in string formatting, making the output more readable and formatted.
person = ("John", 35)
print("My name is %s and I am %d years old." % person)
# Output: 'My name is John and I am 35 years old.'
  • Protecting Data: Since tuples are immutable, they are useful in safeguarding data. The data cannot be changed unintentionally.

Further Reading and Resources

If you’re interested in going beyond what we’ve covered or want to learn Python at a more profound level, here are some useful resources:

  • Python Documentation: The Python official documentation is a comprehensive resource that provides detailed information on each aspect.

Official Python Documentation

  • Python Crash Course, Second Edition: A Hands-On, Project-Based Introduction to Programming by Eric Matthes. This is a great book for those who prefer learning by doing.
  • Automate the Boring Stuff with Python: Practical Programming for Total Beginners by Al Sweigart. This book is fantastic for beginners and focuses on real-world applications of Python programming.

Remember, the best way to master any programming concept, is by constant practice. So keep practicing and happy coding!

Read Also:

Leave a Comment

Your email address will not be published. Required fields are marked *