Python Tuple With Examples

Today we are going to learn about Python Tuple. This is very similar to Python List. If you don’t know about list you can find them here.

Python Tuple

Python tuple is a sequence of Python objects. They are lot like lists. But the differences between a tuple and a list is that tuples can not be changed like we can change an item of a list. Also tuples use parentheses while lists use square brackets.

Python Tuple is a sequence of comma-separated values between parentheses. For example;

Accessing a Value in Python Tuple

Accessing a value in a python tuple is quite similar to the way to access an item in a list. Through index number we can access a value in a tuple. First element has index number zero, second has index number one, and so forth.

The output of the above code will be like below-

tupleExampleAccessingwithNegativeIndex

Tuple in python also support negative indexing like list. A negative index means index number from the right of that tuple.

The output will be like below.

tupleExampleAccessingwithNegativeIndex

Update and Delete in Python Tuple

As we have mentioned earlier tuples in python are not changeable. So you can not update a single tuple element. But we can take two tuple and concat them to create a new one.

Also removing an individual tuple element is not possible. Though we can remove an entire tuple using del statement.

The above code’s output will be like following picture.

Python Tuple

Some built-in Python Tuple Functions

There are some built-in functions available to manipulate tuple in python. Take a look at the following code for understanding.

You should get the following output if you run the above code.

Python Tuple

So that’s it for python tuple. Make sure to run every piece of code on you own. Feel free to leave a comment if you have any doubt.
#happy_coding 🙂

Reference: https://docs.python.org/3.7/tutorial/datastructures.html#tuples-and-sequences

By admin

Leave a Reply