Table of Contents
Introduction to Tuples in Python
A tuples in a Python is a data type in Python which is used to create immutable data. If you’re creating a list of data that is not changeable that you have to create a python tuple. A tuple is a sequence of immutable Python items, Tuples are just like lists.
The differences between tuples and lists
- The tuples cannot be changed (immutable) whereas lists are (mutable).
- The tuples use round brackets, whereas lists use square brackets.
Create a tuple by using round brackets separated by commas.
For example:
Tuple1 = ('SQL', 'Python', 100, 200);
Tuple2 = (1, 2, 3, 4);
Tup3 = "a", "b", "c", "d";
If we pass the nothing in the round brackets then the tuple is empty.
Tuple = ();
To write a tuple containing a single value you have to include a comma, even there is no second value present
Tuple1 = (200,)
Accessing Values in Tuples
To access values in a tuple, use the square brackets with the index or indices to obtain value available at that index.
For Example:
Tuple1 = ('SQL', 'Python', 100, 200);
Tuple2 = (1, 2, 3, 4);
print ("tuple1[0]: ", tuple1[0])
print ("tuple2[1:4]: ", tuple2[1:4])
The output of the above code is:-
tuple1[0]: SQL
tuple2[1:5]: [2, 3, 4]
Updating Tuples in Python
Tuples are immutable which means you cannot update the values of tuple elements.
You are able to take values of existing tuples to create new tuples.
tuple1 = (100, 200);
tuple2 = ('SQL', 'python');
The following action is not valid for tuples.
Tuple1[0] = 100;
Creating a new tuples in Python
We can create a new tuple in python.
tuple3 = tuple1 + tuple2;
print (tuple3)
The output of the above code is:
(100,200,’SQL’,’Python’)
Delete Tuple values
In python removing individual tuple values is not possible.
For Example:
Tuple1 = ('SQL', 'Python', 100, 200);
print(Tuple1)
Del Tuple1;
Print(Tuple1)
The output of the above code is:
('SQL', 'Python', 100, 200);
After delete
NameError: name 'tup' is not defined
Python Expression | Results | Description |
len((100,200,300,400)) | 4 | Length |
(100,200) + (300,400) | (100,200,300,400) | Concatenation |
(‘Fireblaze’,) *2 | (”Fireblaze’, ‘’Fireblaze”) | Repetition |
4 in (2,4,6,8) | True | Membership |
for x in (2,4,6,8): print(x) | 2,4,6,8 | Iteration |
Conclusion
In this article we discussed about tuple .This Blog will help you to get a better understanding of Python Tuple and there uses with examples of tuples in python.