Python tuple

In Python,tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You can use tuple when you know that it won’t change.
In this section, we will get a brief overview of the following:

As this is similar to list, so syntax is also similar but you can not change Tuples.


Create Tuples

The Create of a tuples use () with elements separated by commas. For example:

3

(‘one’, 2)

[4]: ‘one’

 

2

Basic Tuple Methods

Tuples have built-in methods, but not as many as lists do s they are immutable. Lets look at two of them.

0

Use count() to count the number of times a value appears

1

Immutability

You can not change content of tuple. If you try to change it, you will get exception as below

—————————————————————————
TypeError Traceback (most recent call last)
in ()
—-> 1 t[0]= ‘item’TypeError: ‘tuple’ object does not support item assignment

Once tuple is create, it can not be chaned due to immutabllity.

—————————————————————————
AttributeError Traceback (most recent call last)
in ()
—-> 1 t.append(‘item’)AttributeError: ‘tuple’ object has no attribute ‘append’


When to use Tuples

You may be wondering where will you use tuples as it has less inbuilt methods.It is not used as much as list but
it is used sometimes when you don’t want to change the data of tuple for example: days in week.

That’s all about tuples in Python

Leave a Reply

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