Python Tuple Methods

python-tuple-index-methods-1

There are two common methods used with python tuples. In this lesson, we will focus on these Python Tuple Methods. So what are the Tuple Methods used in python? These are:

 

  • Index Method
  • Count Method

 

Index method is used to access the specified item in the python tuple. With this method, we can access any item in the tuple with an index number given in a square brackets. We can also access to a range of items by using one more parameters with index method.

 


You can also check Python List Methods


 

If we use one number, we can access this item only. Let’s show this with an example:

 

cars = ("BMW", "Audi", "Mercedes")
print(cars[1])
Audi

 

You can watch also the video of this lesson!

 

python-tuple-methods-index-method-3

 

 


You can also check Python Tuples versus Python List


 

If we give two parameters divided with colon ( : ), we can access a range of items.

 

cars = ("BMW", "Audi", "Mercedes", "Alfa Romeo", "Aston Martin", "Porche")
print(cars[2:5])

 

('Mercedes', 'Alfa Romeo', 'Aston Martin')

You can practice below!

python-tuple-index-methods-2

 

If we use also the third operator, we can access the range of items and we can also jump on these items.

 

cars = ("BMW", "Audi", "Mercedes", "Alfa Romeo", "Aston Martin", "Porche")
print(cars[2:5:2])

 

('Mercedes', 'Aston Martin')

 

python-tuple-index-methods-1

 

We can also use negative indexes to access any item in the tuple:

 

cars = ("BMW", "Audi", "Mercedes")
print(cars[-1])

 

The output of this python tuple index method will be like below:

 

Mercedes

 

The other method used with python tuples is python count method. With this method, we can count the number of any items in the python tuple.

 

For example, for the below tuple, let’s count 10.

 

numbers = (10,5,14,25,38,10,62,47,10)
x = numbers.count(10)
print(x)

 

As you can see below, the output of this python tuple count method will be 3. Because there are three 10s in this tuple.

 

3

 

python-tuple-count-methods-1

 

In this lesson, we have learned the Python Tuple Methods. You can use these methods for different purposes and for different examples.

Back to: Python Programming Course > Python Tuples

Leave a Reply

Your email address will not be published.

IPCisco is the Winner of 2019 “Best Certification Study Journey” Category! We are also Finalist of 2020 & 2021 in Cisco IT Blog Awards!

Cisco-ITBlogAwards-2019-Winner-IPCisco-k
ITBlogAwards_2020_Badge-Finalist-BestCertStudy-ipcisco
ITBlogAwars-2021-ipcisco

Python Programming Course

Collapse
Expand
IPCisco on Social Media!