Tuples In Python
A tuple just like a list is a sequence of items. The difference between tuples and lists is that lists are mutable, but tuples are not. Once you have defined a list, you can add, remove or modify its items. The same is not true for tuples. Creating a tuple follows the same concept as with lists, but here you need to use round brackets to let Python understand that you are creating a tuple.
Advantages
- We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.
- Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
- Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
- If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
Program on tuples
a=(100,200,300,"prasad","gokul");
print(a);
#tuple can be created without parentheses/tuple packing
b=10,5.6,"oils";
print(b);
a1,a2,a3=b; #tuple unpacking
print(a1,a2,a3);
#nested tuples
c=(10,[1,2,3],(4,5,6));
print(c);
print(type(c)); # prints type of c output <class tuple>
program on tuple with index
v=('v','i','s','i','o','n');
print(v[1]);
print(v[3]);
print(v[2:6]); #prints 2 to 6 chars
n=("vision",[3,4,5,6],(7,8,9,1));
print(n[0][3]);
print(n[1][2]);
print(n[2][2]);
a=('v','i','s','i','o','n');
for i in a:
print(i);
negative indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
Program on negative index
v=('v','i','s','i','o','n');
print(v[-2]);
print(v[-5]);
program on tuple slicing
v=('v','i','s','i','o','n');
print(v[1:4]);
print(v[:-3]);
print(v[3:]);
print(v[:]);
Changing a Tuple
tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed
a=(10,20,30,[40,50,60]);
print(a);
#a[1]=30; no assignment to tuples
a[3][1]=90;
print(a);
Delete tuple: tuples can’t be deleted but using del we can delete the entire tuple
Program on delete tuple
a=(10,20,30,[40,50,60]);
print(a);
del a;
print(a); # error a is deleted completely
tuple methods
Return the number of items that is equal to x |
|
Return index of first item that is equal to x |
Program on tuple methods
a=('v','i','s','i','o','n');
print(a.count('i'));
print(a.index('i'));
tuple with membership operators
a=('v','i','s','i','o','n');
print( 'i' in a);
print('s' in a);
print('k' in a);
print('m' not in a);
Functions with Tuple
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), tuple() etc. are commonly used with tuple to perform different tasks.
Program on functions with tuple
a=('v','i','s','i','o','n');
b=sorted(a);
print(b);
print(len(b));
For
Online Classes
Contact Us: 9885348743
Online Classes
Contact Us: 9885348743