Tuple are similar to List but the
data inside the Tuple cannot be changed once created. Un like List this is a immutable Object.
Similarly as List the elements in Tuple can be accessed using indexing.
A Tuple can be created using,
days = ("Sunday",
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday")
And a Single Item Tuple can be
created using
>>> st = (1,)
>>> st
(1,)
Some More examples of Tuple are
# empty tuple
my_tuple = ()
# tuple having integers
my_tuple = (1, 2, 3)
# tuple with mixed datatypes
my_tuple = (1,
"Hello", 3.4)
# nested tuple
my_tuple = ("mouse",
[8, 4, 6], (1, 2, 3))
# tuple can be created without
parentheses
# also called tuple packing
my_tuple = 3, 4.6,
"dog"
# tuple unpacking is also
possible
a, b, c = my_tuple
Tuple repitition which is like
the following.
print (1, 2) * 4
Tuples can be heterogeneous and they can be created
using,
t = (0,1,"two",3.0,
"four", (5, 6))
Accessing - A
Tuple can be accessed similarly as List using the Indexing as,
>>>tup1 = (1, 2, 3, 4,
5, 6, 7 );
>>> print
"tup1[0]: ", tup1[0]
Deletion – Since a Tuple is an
immutable Type , the Tuple elements cannot be deleted. To delete a entire Tuple
we can use,
tup = ('physics', 'chemistry',
1997, 2000);
del tup;
All Other Operations Like
Concatenation, Repetition are allowed on The Tuple like List
Unpacking – a Tuple
can be unpacked into several values and can be assigned as
>>> v =
("x","y","z")
>>> (a,b,c) = v
>>> print a
x
>>> print b
y
>>> print c
Z
Comparing -
Multiple Tuples can be compared as
Compare two tuples
>>> print (4,2) <
(3,5)
False
>>> print (2,4) ==
(2,4)
True
No comments :
Post a Comment