Tuple Functions In Python
A tuple is a sequence of inflexible Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples can not be changed unlike lists. Tuples use hiatuses, whereas lists use square classes.
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,)
Streamlining Tuples
Tuples are inflexible, which means you can not modernize or change the values of tuple rudiments. You're suitable to take portions of the being tuples to produce new tuples as the following illustration demonstrates −
#!/usr/bin/python3 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)
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To pierce values in tuple, use the square classes for slicing along with the indicator or indicators to gain the value available at that indicator. For illustration −
#!/usr/bin/python3 tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the following result −
tup1[0]: physics tup2[1:5]: (2, 3, 4, 5)
Comments
Post a Comment