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
The second one using tuple() constructor function.
The third one is to create a tuple without parenthesis from first method.
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
Access the second element t
and so on.
Changing a Value of Tuple
It will will raise an error.
Accessing Elements From a Tuple Using Negative Indices
You can access the last element using -1 index.
You can access the second last element using -2 index.
index() and count() Functions for a Tuple
index() function returns the index of an element of first occurrence.
See an example
count() function returns numbers of occurrences of an element.
See an example
Changing a Tuple to a List
list() constructor function is used to convert a tuple to a list.
Again you can convert list l into tuple using tuple() constructor.
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)