import sys numbers = (1, 5, 23, 67, 2, 456, 87) numbers_list = [1, 5, 23, 67, 2, 456, 87] print(sys.getsizeof(numbers)) print(sys.getsizeof(numbers_list))
The sys.getsizeof() function returns the size of a Python object in bytes. So, if we print the output of the above program, the output should look like the following:
96 120
So, if we want to store a huge number of Python objects, tuples will be much more memory efficient than lists. Please note that tuples are immutable. So, once we initialize a tuple, we cannot add, delete or update the items stored in the tuple anymore.
How to access an item stored in a Python tuple?
Python objects stored in a tuple are ordered. So, we can use an index to refer an item stored in a tuple. For example,
book = ("A Guide To Python", "John A.", 1, 2020)
print(book[1])
The above program stores the information related to a book in the tuple “book”. The first item is the name of the book, the second item is the name of the author of the book, the third one is the edition number of the book and the fourth item is the year of publication of the book. Here, we are using book[1] to print the name of the author of the book. The output will be the following:
John A.
Does a Python tuple allow duplicates?
Python tuples allow duplicates. For example,
numbers = (1, 5, 23, 67, 2, 456, 87, 5) print(max(numbers))
Here, the number 5 has a duplicate entry in the tuple “numbers”. And, we are using a built-in tuple function max() to find out the maximum number stored in the tuple. The above program will print the following output:








































0 Comments