Let’s say we have a huge list of numbers. We want to operate on the list of numbers in such a way that the list of numbers remains unchanged during the operation. For example, let’s say we want to find out the maximum and minimum k numbers from the list of numbers. One way to solve this problem will be to store the numbers in a Python list and then operate on the list. But, in Python, lists are mutable and it takes comparatively more space in memory. So, we can use a Python tuple instead.
In Python, a tuple is a data type that can store a number of Python data types like strings, integers, booleans, etc. And, a tuple is immutable. In other words, once a tuple is initialized, the items in the tuple cannot be changed afterward.
Let’s look at a simple example of a tuple.
numbers = (1, 5, 23, 67, 2, 456, 87) maximum = max(numbers) print(maximum)
The above program stores a list of numbers in a tuple called numbers. Then, it operates on the tuple and finds out the maximum number stored in the tuple. It uses the built-in function max() for this purpose. The above program will print the following output:
456
Why should we use a tuple in Python?
Now, why should we use a tuple in Python? As I said, a tuple takes comparatively less space in memory than a list. So, if we want to store a huge number of Python objects and do not want to change the stored objects later, then tuples will be much more memory efficient. Let’s write a small program to find out how memory-efficient tuples are.






0 Comments