Accessing index and value in Tuples | Python
Tuples
Tuples consist of a number of values separated by a comma and enclosed within parentheses(). A tuple is similar to a list, values in a list can be changed but not in a tuple.
A Tuples is also an ordered, indexed, and sequence data type. A list is an immutable data type (unchangeable). The elements cannot be modified.
Now, we know that Tuples are immutable(unchangeable). But, some limited operation possible in Tuples.
- Update Tuple
- delete Tuple
Update Tuple
We already know that tuple is immutable(The values in the tuple is not changeable). But we can extend the values of one tuple to another tuple.
Example:
- >>>tup1=(1,2,3,4,5)
- >>>tup2=(6,7,8)
- >>>tup1+tup2
- (1,2,3,4,5,6,7,8)
Delete Tuple
Tuple is an immutable data structure, you cannot delete particular values or elements from the tuple. But it allows to whole tuple.
Example:
- >>>tup=(“Iterathon”)
- >>>del tup
- >>>print(tup)
- NameError: name ‘tup’ is not defined
Accessing Values in Tuple
we already saw some basic access of data types. Same concept also used for accessing tuples with slicing.
Example 1:
- >>>tup=(1,2,3,4,5,6)
- >>>print(tup[2:4])
- (3,4)
Example 2:
- >>>tup=(1,2,3,4,5,6)
- >>>print(tup[:])
- (1,2,3,4,5,6)
Some Tuple operations
- len()
- concatenation
- max()
- min()
- Repetition
len()
len() returns a how many elements are there in the tuple. It is differ from index.
Example:
- >>>tup=(1,2,3,4,5)
- >>>print(len(tup))
- >>>5
Concatenation
concatenation is used to adds the elements in tuple to the end of another tuple. That is concatenated (+ or +=) both tuple.
Example:
- >>>tup=(1,2,3,4,5)
- >>>tup1=(5,6)
- >>>print(tup+tup1)
- >>>(1,2,3,4,5,6)
min()
min() returns minimum or lowest value in the tuple.
Example:
- >>>tup=(1,2,3,4,5)
- >>>print(min(tup))
- >>>1
max()
max() returns maximum or highest value in the tuple.
Example:
- >>>tup=(1,2,3,4,5)
- >>>print(max(tup))
- >>>5
Repetition
repetition is used to multiply a given tuple.
Example:
- >>>tup=(1,2,3,4,5)
- >>>print(tup*2)
- >>>(1,2,3,4,5,1,2,3,4,5)
Typecasting
Typecasting is used to convert one datatype to another.
list [] to tuple() and tuple() to list[]
In the above image is a clear example for type casting. This is not only for list and tuple and also for all data type. we will see in upcoming blogs.
My Previous Post
Important List Operations in Python: https://iterathon.tech//important-list-operations-in-python/
LEARN LITTLE BY LITTLE TO CHANGE THE TECH WORLD