fbpx

In this article, we will learn python tuple creation , basic tuple functions and it’s immutability. Python Tuples are very similar to Python list . Only difference is , Tuple are immutable means once created , can not be changed.

1. learn python tuple creation

You can create a tuple by enclosing elements within parentheses and separating them with commas. Below code create a Tuple :

Let’s check the type of the tuple we just created :

2. learn python tuple Elements access using indexing

We can access Tuple elements using indexing similar to string or list . Let’s access 4th element in the tuple

Try to pull 5th element from this tuple and see what happens . As tuple stored till index 3 , so any index outside of 0-3 will give tuple index out of range error.

If we want to access First two char of the name stored in the tuple. By using my_tuple[3] we get the name string and then we can use slicing to get first two char of the string.

3. learn python tuple immutability

Immutability make tuple different from List . This means one should generally use List until have a case where one don’t want their list to be changed . In Python dictionary , if you have to create key as list or tuple , then tuple would be a good choice as key . You can see in below code ,we will hit an error saying item assignment not allowed in case of tuple.

4. Python tuple functions

Tuples have a limited set of methods due to their immutability, but you can still perform operations like:
count(): Counts the number of occurrences of a specific element.
index(): Finds the index of the first occurrence of a specific element.

You can find the count of element present in python tuple using count function .

You can find the index of any element present in python tuple using index function .

More Resources :

Want to Learn Python from our Expert . Check this out .

Don’t trust us , See if you like learnpython.com

By tecksed

Leave a Reply

Your email address will not be published. Required fields are marked *

×