Tutorials

0
Tuples are sequences, just like lists. The only difference is that tuples can't be changed i.e., tuples are immutable and tuples use parentheses and lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also. For example:
tup1 = ('pranav', 'nandankar', 1996, 2016)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is written as two parentheses containing nothing:
tup1 = ()
To write a tuple containing a single value you have to include a comma, even though there is only one value:
tup1 = (50,)

Accessing a Value:

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. Following is a simple example:

tup1 = ('pranav', 'nandankar', 19966, 2016)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

Output:

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]


Updating Tuples:

Tuples are immutable which means you cannot update them or change values of tuple elements. But we able to take portions of an existing tuples to create a new tuples as follows. Following is a simple example:
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')

# Following action is not valid for tuples
# tup1[0] = 100

# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)

Output:

(12, 34.56, 'abc', 'xyz')

Delete Tuples Elements:

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. 
To explicitly remove an entire tuple, just use the del statement. Following is a simple example:


tup = ('pranav', 'nandankar', 1996, 2016)
print tup
del tup
print "After deleting tup : "
print tup

Output:

('pranav', 'nandankar', 1996, 2016)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup
NameError: name 'tup' is not defined



Post a Comment

 
Top