Tuples in Python

Tuples in Python

Tuples in Python

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
>>>t[0] Output:1
Access the second element t
>>>t[1] Output:2
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.
>>>t[-1] Output:6

You can access the second last element using -2 index.
>>>t[-2] Output:5

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
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.

Using these two constructors  you can first convert a tuple into list and modify and then again convert to tuple t .

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)

Share to Your Friend

Leave a Comment