Python Tuples
Tuple is a collection of objects, separated by comma and are placed in parentheses. Which are immutable.
Any sequence in '()' represents tuple.
Ones tuple is declared or initialized it can not be updated or modified.
Initialization of Tuple
There are 2 ways to initialize tuple.
Direct way of initializing tuple
Comma separated sequence is placed in parenthesis and in this way the tuple is initialized, as follows.
Program
Using tuple() method
The collection of objects are placed in a square bracket or in parentheses, and are passed as an argument to the tuple() method.
Program
Operations with tuple
Before going further keep in mind that, tuples are immutable i.e. Once tuple is declared or initialized, it can not be updated or modified ( elements can not be added or removed after declaration or initialization of tuple).
Program
Trick to modify a tuple
Follow the following steps to modify a tuple.
- Convert a tuple into a list, by using list() method.
- Do the modifications.
- Then convert it again into tuple, by using tuple() method.
Accessing elements in tuple
Elements can not be added or removed but, it can be accessed.
Accessing an element in tuple
Provide index to access an element in a tuple.
Program
Accessing element with negative number in tuple
It's useful when accessing an element from the end of a tuple.
Use '-1' to access the last element, '-2' to access the second last element and soo on.
Program
>>> num = ('zero', 'one', 'two', 'three')
Accessing elements in tuple (range)
In tuple, more elements can be accessed by specifying range.
Syntax / format :-
tuple_name[start index: end index]
Start index :- start the selection from the index
End index :- till where the selection should be done.
Note:- this value is not included.
Program
Program
>>> a = (1, 2, 3, 4, 5, 6)
Program
>>> a = (1, 2, 3, 4, 5, 6)
When both starting index and ending index is not specified, then whole tuple is returned.
Program
Accessing elements in an interval.
Syntax / format :-
typle_name[start index: end index: steps]
Steps :- interval.
Program
>>> a = (1, 2, 3, 4, 5, 6)
Program
>>> a = (1, 2, 3, 4, 5, 6)
Range accessing with negative number in tuple
Selection of elements ranging last in a tuple, by using negative indexing.
Program
Joining two or more tuples
Use '+' operator to join tuples.
Joining two tuples.
Program
Program
>>> st = ("Hello", "world")
Tuple length
Use 'len()' built-in function to know the length of a tuple.
Program
Python tuple count() build-in function
Returns number of occurrences of an element in a tuple.
Program
Python tuple index() build-in function
The index(), tuple's built in function, returns the index of a value.
Program
إرسال تعليق
If you have any query, feel free to ask.