A tuple in python is a sequence of immutable objects. If you know how list works then you can easily understand how tuples in python work. They’re just like lists but they can’t be changed.
What are Tuples ?
- Tuples are immutable objects (you can’t change it like lists)
- Python Tuple make use of parentheses.
- Tuples indices start at 0.
- Tuples can be concatenated.
- They can be sliced like python lists.
How to Create Tuples
It is very easy to create tuples. A simple tuple can be created like this:
tupn=(); This is empty tuple. tupsingle=(1); tup1=('a',1,'b',2,'c',3); tup2=(5,6,7,8);
Note that when you use strings you need to add them in single quote. You don’t have to add quotes for the numbers.
You can print the tuples like this:
print tupn(); print "tup1",tup1; print "tup2[0:4]",tup2[0:4];
Updating Tuples
Tuples can’t be changed easily and for that reason you can only use the objects from existing tuples and create new tuples. You can use individual object from the tuple and add or update in new tuple.
Deleting Tuple Elements
Tuple elements can’t be changed or deleted. You can however delete an entire tuple and start over gain. By using “del” you can delete entire tuple.
del tup1
This will delete the tup1 and when you go on printing this tuple it’ll throw an error.
Finding Length of Tuple
You can find the length of tuple with len() function.
len(tup1);
Comparing the elements of Tuple
Use cmp() function to compare the tuples. Just place the two tuples in this function.
cmp(tup1,tup2);
Convert List into Tuples
Use tuple() function to convert the list into tuple. For example –
tuple(list);
this will change the list into tuple.
This completes our short tutorial on python tuples. Hope this helps to those who are learning about python tuples and lists. If you have any questions then feel free post comments or send me a tweet at @maheshkale.