Learn everything about tuples
Python list is a very simple and go-to choice due to its mutability feature and ease of use. But there is one more data structure that Python offers that is equaly useful and incredible. Tuple. Tuple is immutable data sequence with distinct advantages that make it a valuable tool for some use cases. In this chapter, we will dive into tuple data structure, find answers for the below questions:
- What is tuple?
- How to create tuple in python?
- How to access tuple elements?
- What are the differences between a list and tuple?
- Where can we employ tuples effectively?
So, are you ready for the journey into the Python's Typle Data Structure?
yes, let's get started.
Tuples: The Immutable Sequences
Python tuple is a data structure that stores the collection of elements of various data types in order. The primary distinction between tuple and list reside in their mutability. While we can modify list after it has been created, tuple is immutable, meaning the elements cannot be changed, added, or removed once the tuple is created. This means the value is constant and can not be changed during the lifetime of a program. This immutability makes tuples ideal for scenarios where data integrity and safety are crucial. For example, data retrived from a database table.
Did you ever notice what it returns is a list of tuples?
Let me know in comments if you knew this or you checked it after reading this.
My next question to you is why it uses list of tuples for database table records? Why not list of lists or tuple of lists or tuple of tuples?
Think about it. 😇
Meanwhile, let's look at how we can create and access tuple elements.
Creating and Accessing Tuples
Creating tuples is straightforward; we can define a tuple by enclosing its elements in parentheses ()
and separating elements with comma. Let us look at a simple example:
# Simplest way of creating tuple of strings
fruits = ('apple', 'orange', 'banana', 'grape')
We can access the tuple elements same as we access a list element. We can use indexing and slicing to retrieve specific elements or a subset of elements from the tuple. For instance:
# Accessing elements in a tuple
print(fruits[0]) # Output: 'apple'
print(fruits[1:3]) # Output: ('orange', 'banana')
Tuple Packing and Unpacking
Tuple packing and unpacking are potent features in Python. Packing involves assigning multiple values to a single tuple, whereas unpacking allows us to extract values from a tuple into individual variables. Consider this example:
# Tuple packing
point = (10, 20)
# Tuple unpacking
x, y = point
print(f"x: {x}, y: {y}") # Output: x: 10, y: 20
Difference Between List and Tuple
While both list and tuple store collections of items, their unique characteristics make them suitable for different scenarios. Here are some key differences and best use cases for each:
- Lists
- Lists are mutable, allowing for easy modification of elements.
- They use more memory than tuples due to the overhead of additional functionalities.
- Ideal for situations where data needs to be frequently modified, such as a to-do list.
- Tuples
- Tuples are immutable, ensuring data integrity and safety.
- They are slightly more memory-efficient than lists.
- Well-suited for representing fixed data, such as coordinates, RGB values of colors, or database records.
Best Use Cases
Consider the following example to demonstrate the best use cases for tuples:
# Using a list for a to-do list
to_do_list = ["Task 1", "Task 2", "Task 3"]
to_do_list[1] = "Task 2 (Completed)"
# Using a tuple for coordinates
coordinates = (10, 20)
# coordinates[0] = 5 # This will raise an error as tuples are immutable
Tuple Internals
Tuple Object Structure
PyTupleObject
struct, which contains the following members:ob_refcnt
: reference countob_type
: type objectob_size
: size of the tupleob_item
: array of pointers to Python objectstypedef struct {
PyObject_VAR_HEAD
PyObject *ob_item[1];
} PyTupleObject;
When you create a tuple, Python allocates memory for the tuple object and initializes the ob_item
array with pointers to the objects you're storing in the tuple.
Consider the following tuple:
my_tuple = (1, 2, 3)
Internally, Python creates a tuple object with ob_size
set to 3 and ob_item
pointing to an array of three pointers:
item[0]
: pointer to the integer object 1
item[1]
: pointer to the integer object 2
item[2]
: pointer to the integer object 3
Benefits
Interview Question
Why Tuple is faster than list?
Looking forward to your answers in comment section.
Conclusion
Tuples are valuable to Python's data structures, providing immutability and efficient data handling capabilities. While lists remain popular for general-purpose data storage and manipulation, tuples shine in scenarios where data integrity, safety, and memory efficiency are paramount. By understanding the strengths and best use cases of tuples, Python developers can make informed decisions on when to employ tuples to their advantage, streamlining their code and enhancing overall performance.
So, when dealing with fixed data or ensuring data immutability, consider the power and simplicity of tuples in Python. Happy coding!
Reader Comments
Add a Comment
Recent Posts
- How To Use Variables and Data Types in Python Programming
- Learn Basic Input and Output in Python by Example
- Learn and Master Operators and Expressions in Python
- How To Use Loops in Python?
- How To Use Modules and Packages in Python?
- How To Do File Handling In Python?
- How To Handle Exceptions In Python?
- How To Manipulate String in Python?
- How To Use Regular Expression In Python?
- How To Write Object-Oriented Programs (OOP) in Python?
- How To Create Classes and Objects In Python?
- How To Use Python Dictionaries?
- How To Inherit A Class In Python?
- A Journey into Python Programming | Power of Python Programming
- How To Use Conditional Statements in Python?
- How to define functions in python?
- Master Python List and Its Essential Functions