I would like to give you an overview of how tuples can be used in Python. Tuples are ordered and unchangeable/immutable. Tuples are used when we want to group certain items together.
List | Tuple |
The item on the list can be updated | Items cannot be changed |
[] paranthesis | () parenthesis |
deleting an item in the list can be done | Cannot delete an item in tuple |
less memory efficient | more memory efficient because it is immutable |
You can declare an empty tuple as follows.
emptyTuple = ()
We can group various data types together in tuple.
Table of Contents
1. Simple Example
input = ("This is a string", 5.6, 0,'T', -8)
print(input)
#output
('This is a string', 5.6, 0, 'T', -8)
2. Example of Tuple containing list/ tuples
We can have sub tuples, lists, dictionaries inside a tuple. I have an example for you.
example = ((1,2,3), [9,10,11], "this is string data type")
print(example)
#output
((1, 2, 3), [9, 10, 11], 'this is string data type')
In this section, I am going to discuss tuple unpacking. Let us see what tuple unpacking is.
student = ("John", 14, "Python")
(name, age,course) = student #tuple unpacking
print(name)
print (age)
print (course)
#output
John
14
Python
We see that when we do an unpacking operation on tuple it will assign to the individual variables like name , age and course.
Like a list, in tuples we can access the item of the item by positive index or negative slicing.
example = ((1,2,3), [9,10,11], "this is string data type")
print(example[0]) #accessing the tuple with positive index
print(example[-1]) #accessing the tuple by negative slicing
# output
(1, 2, 3)
this is string data type
You can use negative slicing when you want to access the item starting from the end to the start. We can access the last element as -1, the second last element is accessed as -2, and so on.
We can delete the entire tuple by using the delete operation.
del(input)
By using del we have deleted the tuple from the memory.
Other useful functions supported by tuples
- We access the length of the tuple by using len() function.
- Although tuple is immutable, when there is a list as one of the items, then the list is mutable.
- You can loop through a tuple by using for or a while and perform various actions using the values.
- We can perform multiplication and addition on the tuples by using the * and + operator.
- You can perform some of the math operations on the tuples by using max(tuple) to get the largest element in the tuple and min(tuple) to get the smallest element.
- You can compare tuples by using cmp(t1, t2) where it verifies if the 2 tuples have the same contents. This function returns:
- 1, when t1 < t2.
- 0, when t1 = t2.
- -1 when t1 > t2.
In conclusion, the main thing to remember is they are immutable.
Click here to code and run programs yourself. Have fun!