Tuples in Python
Tuples in Python are ordered collection of items(integer, float, string) which are immutable. The only difference from list you can notice that a tuple in Python is immutable.
Further, it uses parenthesis to create a tuple. However, tuples can also be created without parenthesis separated by comma.
Now open terminal or jupyter notebook.
Create a tuple t having 6 elements.
Creating a Tuple
There are three ways to create a tuple
The first one using parenthesis
>>>t=(1,2,3,4,5,6)
The second one using tuple() constructor function.
>>>t=tuple([1,2,3,4,5,6])
The third one is to create a tuple without parenthesis from first method.
i.e.
>>>t=1,2,3,4,5,6
Note: Comma is mandatory
Among three the first one is popular.
Accessing Elements From a Tuple
To Access elements from a tuple indexing is used.
Access the first element from t
>>>t[0]
Output:1
Access the second element t
>>>t[1]
Output:2
and so on.
Changing a Value of Tuple
>>>t[1]=7
It will will raise an error.
Accessing Elements From a Tuple Using Negative Indices
You can access the last element using -1 index.
i.e.
>>>t[-1]
Output:6
You can access the second last element using -2 index.
i.e.
>>>t[-2]
Output:5
index() and count() Functions for a Tuple
index() function returns the index of an element of first occurrence.
If
>>>t=(1,2,3,4,5,6,7,6)
See an example
>>>t.index(6)
Output:5
count() function returns numbers of occurrences of an element.
See an example
>>>t.index(6)
Output: 2
Changing a Tuple to a List
list() constructor function is used to convert a tuple to a list.
l= list(t)
Again you can convert list l into tuple using tuple() constructor.
t=tuple(l)
Concatenating Two Tuples
Using + sign two tuples can be created.
Suppose you create a tuple t1=(1,2,3,4,5,6)
and another tuple t=(7,8,9,10)
Then
>>>=t3=t1+t2
>>>print(t3)
Output:(1,2,3,4,5,6,7,8,9,10)