Tuples – Basics and Methods

Tuples:

Tuples are very similar to lists, but they have one key difference – They are immutable. Once an element is inside a tuple, it can not be reassigned or deleted.

Tuples are denoted by parentheses – () Let’s make a tuple.

first_tuple=(1,2,3,4,"hello",4.56)
print(first_tuple)

And when we run it, our tuple gets printed-

(1, 2, 3, 4, 'hello', 4.56)

As we see above, tuples can contain multiple object types as well. Indexing in case of tuples works the same as in the case of lists.

In case of tuples, there are a very less number of methods that exist, owing to the fact that they are immutable. In fact, there are only 2 methods. Let’s look upon them-

The count() Method:

We are given the tuple-

freq_count=(1,1,1,2,3,5,1,1)

And, we are given the task of counting the number of 1’s that are present in it. The count method will help us in achieving this task.

count_num = freq_count.count(1)
print(count_num)

It returns the frequency or count back to us, which we can store in a variable. When we run the above piece of code, we get-

5

The index() method:

The index returns the index of the the first appearance of an item in a tuple. Let’s take the above tuple, and try to find the indices of 1 and 5.

index_1=freq_count.index(1)
index_5=freq_count.count(5)
print(index_1,index_5)

And we get the following output-

0 5

Which are the indices of the first appearance of 1 and 5 in the tuple freq_count respectively.

Type Error

Reassignment of an item in a tuple gives a Type Error.

Data Integrity or Non-changeability

Since, we cannot change a tuple, they play an important role whenever we have to move data around in our program without letting it change. In future, we will need these kind of data types a lot.

Tuple Constructor:

Never mind what a constructor is for now, just think of it as a technical word!

Now, suppose we want to convert a list (or any other plausible data type) into a tuple. Then we can do it as follows-

my_list=[1,2,3,4,5]
print(my_list)
my_tuple=tuple(my_list)
print(my_tuple)

When we run the program, the list gets converted to a tuple and we get the following output-

[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)

Length of a Tuple:

We can find the length of a tuple using the len() function. Let’s take the tuple first_tuple as defined above, and print it’s length.

print(len(first_tuple))

And we get the following output-

6

Finding an item in a tuple-

We can check if an item exist in a tuple by using the in keyword as follows-

check_1= 1 in first_tuple
print(check_1)
check_100= 100 in first_tuple
print(check_100)

And we get the following output when we run the above code-

True
False

As we have seen before, in returns the boolean value, which is True if the object or element is present in the tuple and False if it is not.

That’s it folks!

Tuples – Basics and Methods