Tuples :
Tuples are immutable list data structures in python. They are like lists but the only difference is, you can not change the content of the tuple unlike lists. Tuples are built-in data structures like lists.
These are useful at the times when you need to use the data structures which could not be modified at some situations..
Tuple is a immutable sequence of python objects.
Creating tuple:
Tuple can be created by putting comma-separated values. you can also put comma separated values between parenthesis.
Examples:
tuple1 = ("India", "America", "France", "Russia", 2020, 1947);
tuple2 = ( 2, 3, 5, 7, 11, 13);
tuple3 = "a","b","c","d","e";
Empty tuple:
tuple = ( );
Like strings and lists tuple indices start from 0
The tuple indices can be Sliced, concatenate, and so on.
Accessing Tuple:
To access values in tuple, use square brackets for slicing along with index or indices for the values of particular index.
Example: There are two tuples tuple1 and tuple2
tuple1 = ("India", "America","Japan", "Germany",2020);
tuple2 = (2,3,5,7,11,13,17);
compute: tuple1[0] and tuple2[1:5]
Output:
Updating tuple : Tuples are immutable lists, you can not change the contents/items of any tuples.
portions of the tuple can be taken to create new tuple.
Example : take two tuples tup1 and tup2 populated with following items
tup1 = (12, 24, 36, 48);
tup2 = ('Pre' , 'post');
now, perform
tup12 = tup1 + tup2
Output :
Deleting tuple:
- Individual tuple element can not be deleted.
- You can do it by creating new tuple, dropping the individual element.
- use del keyword to delete the tuple.
Example : take tuple1
tuple1 = ("India", "America","Japan", "Germany",2020);
delete this by using
del tuple1;
Output:
Tuple Operations:
- Length : Length of the tuple
e.g. len (1,2,3) will return 3
- Concatenation: concatenates two or more tuples
e.g (1,2,4,5) + ( 6,7,8) will result
(1,2,4,5,6,7,8)
- Repetition: Use astrisk (*) followed with number to repeat
e.g. ('Hello',) * 3 will return
('Hello','Hello','Hello')
- Membership: gives TRUE if the element is a member or FALSE if it is not the member.
e.g. 4 in (1,2,3,4,5) will result TRUE
while 6 in (1,2,3,4,5) will result FALSE
- Iteration:
Indexing and slicing
Indexing and slicing works the same way as it does in strings.
you can refer to the post Lists in Python
Buil-in Tuple Functions:
- cmp
compares two strings . it returns boolean value
cmp (tuple1 , tuple2)
- len
returns the length of tuple or items/elements in the tuple
len (tuple1)
- max
returns item from the tuple with maximum value.
max(tup1)
- min
returns item from the tuple with minimum value.
min(tup1)
- tuple(seq)
converts a list into tuple
No comments:
Post a Comment