What is Tuple in Python?

Published by Anshul Verma on

What is Python Tuple - Creating, Functions, Methods, Operations

Python programming language has various data types including lists, sets, dictionaries, etc. Python also comes with a collections package that has specialized data structures. Tuple in python is also one of the collection data types that is popular. In this article, we will learn about tuples in detail with examples. Following are the topics covered in this blog:

What is Python Tuple - Creating, Functions, Methods, Operations

What is A Tuple?

A tuple is an immutable data type in python, almost similar to a list in python in terms of indexing and having duplicate members. It is a collection data type that stores python objects separated by commas. Following is an example of how we can create or declare a tuple in python.

#creating a tuple

a = (‘python’, ‘anshul’)

#another approach

b = ‘python’ , ‘verma’

print(a)

print(b)

Output: (‘python’ , ‘anshul’)

(‘python’ , ‘verma’)

Accessing Items In A Tuple

Accessing items in a tuple works similar to a list, we can access elements in a list using indexes. We can specify the index value and it will return the item stored at that particular index value.

Indexing

It is a data structure technique to effectively retrieve information from a data structure. In python, several data types support indexing like lists, string, etc.

For example, let’s just say we have a tuple with 5 natural numbers as members. So the indexing will start with the value 0 where 1 will be stored and it will go until the end of the tuple i.e 5 and the index value at 5 will be 4.

Take a look at the example below to understand how we can access elements in a tuple using indexing

a = (‘ml/ai’, ‘python’ , ‘data structure’ , ‘collections’)

print(a[1])

print(a[3])

Output: python

collections

As you can see in the above example, we are able to get the elements stored at the index values 1 and 3. Similarly, we can access any value inside a tuple using index values.

Negative Indexing

In python, we can use negative indexing as well to access elements in a tuple or any other data type that supports indexing.

a = (1,2,3,4,5,6,7,8,9,10)

print(a[-4])

print(a[-1])

Output: 7

10

Slicing

It is a technique in which we use the slicing operator ‘:’ to get a range of elements from a tuple or any other data type that supports indexing for accessing elements.

a = (1,2,3,4,5,6,7,8,9,10)

print(a[1:8])

print(a[1:])

print(a[:5])

Output: (2,3,4,5,6,7,8)

(2,3,4,5,6,7,8,9,10)

(1,2,3,4,5)

In the above example, the index value before the slicing operator is the starting index and the index value after the slicing operator is the value that will not be included in the output.

Only until the value before the ending index will be included in the output. We can even use the negative index values with the slicing operator to get the range of values from the tuple.

a = (1,2,3,4,5,6,7,8,9,10)

print(a[-8:])

Output: (3,4,5,6,7,8,9,10)

Changing A Tuple

Even though tuples in python are immutable in nature, a nested object in a tuple can be changed. Or in general, a tuple in python can be reassigned with a different value.

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

a[3][0] = 14

print(a)

#reassigning the value

a = (‘anshul’, ‘python’)

print(a)

Output: (1,2,3,[14,5])

(‘edureka’, ‘python’)

Concatenating Two Tuples

Joining two tuples is a very easy task. You just to assign the addition of the two tuples to another variable and it will return the concatenated tuple with the values of both the tuples. Consider the example below to understand this.

a = (1,2,3,4,5)

b = (6,7,8,9,10)

c = a + b

print(c)

Output: (1,2,3,4,5,6,7,8,9,10)

As you can see in the example, the concatenated tuple contains the values of both the tuples a and b.

Deleting A Tuple

Being an immutable data type, a tuple in python does not allow any changes and you cannot even remove an element from a tuple after the declaration. But there is a keyword ‘del’ which will delete the tuple altogether.

a = (1,2,3,4,5)

del a

print(a)

You will get a Name error if you run the above program because there is no tuple named as present since we have deleted it.

Tuple Methods

Following are the tuple methods that we can use while working with a tuple in python.

  • count: Returns the count of the items.
  • index: It returns the index of the item specified.

a = (1,2,1,3,1,3,1,2,1,4,1,5,1,5)

print(a.count(1))

print(a.index(5))

Output: 7

11

List vs Tuple

List Tuple
Used for homogenous data types Generally used for heterogeneous data types
Mutable in nature Immutable in nature, which helps in faster iteration
Does not have immutable elements Immutable elements can be used as a key for a dictionary
No guarantee that the data is write-protected Implementing a tuple with data that does not change guarantees that it is write-protected

Iterating Through A Tuple

Using a for loop we can iterate through a tuple in python. The following example shows how we can iterate through a tuple using a for loop.

a = (“python”, “for data science”, “for Artificial Intelligence”)

for i in a:

print(“python”, i)

Output: python python

python for data science

python for artificial intelligence

Tuple Constructor

It is possible to create a tuple using a tuple() constructor as well. We can even use the tuple constructor to change a list to a tuple.

a = [1,2,3,4,5]

b = tuple(a)

print(b)

c = tuple((‘anshul’, ‘python’))

print(c)

Output: (1,2,3,4,5)

(‘anshul’, ‘python’)

Membership Test In A Tuple

Using the membership operator ‘in’ in python we can check whether an element is present in a tuple or not. The following example shows how we can check if an element is present in a tuple or not.

a = (1,2,3,4,5,6,7,8,9,10)

print(6 in a)

print(15 in a)

Output: True

False

Python Tuple Functions

A lot of functions that work on lists work on tuples too. A function applies on a construct and returns a result. It does not modify the construct. Let’s see what we can do.

 Python Tuple Functions

Python Tuple Tutorial – Python Tuple Functions

Advantage over List

Lists and tuples in Python are typically used in similar situations. But tuples are preferred over lists due to a variety of reasons. Some of them are listed below. Tuples are used for heterogeneous types of data. On the other hand, lists are more suitable for homogenous data types. Tuples offer a performance boost as iterating through them is faster as compared to lists. This is attributable to their immutable nature. You can go for tuple implementation to keep your data write-protected. Immutable elements can be used as a dictionary key.

This brings us to the end of this article where we have learned how we can use tuple in python and how we can access the elements in a tuple using indexes with various other examples. I hope you are clear with all that has been shared with you in this tutorial.

Till then, Stay Safe, Stay Happy & Keep Coding…

IF YOU WANT TO KNOW ABOUt DATA SCIENCE click here.

CONNECT WITH THE AUTHOR ON LINKEDIN.

VISIT OUR WEBSITE BRIGHTERBEES FOR MORE INTERESTING STUFFS ABOUT LEARNING.

Categories: Python

12 Comments

Portal · December 23, 2020 at 3:33 PM

Wow actually a great post. I like this.I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him. Overall, Lots of great information and inspiration, both of which we all need!

antiquate · January 3, 2021 at 5:36 AM

Everything is very open with a рrecise explanation of the issues.
It was definitely informative. Your ԝebsite is useful.
Thanks for sharing!

dover · January 10, 2021 at 1:52 PM

Keep оn ᴡriting, great job!

anomic · January 11, 2021 at 7:00 PM

I hаve been explօring for a little for any high-quality articles or weƄlog p᧐sts in this
sort of arеa . Exploring in Yahoo I finaⅼly
stumbled upon this wеb site. Studying this info So i am glad
to ѕhow that I have a very good uncanny feeling Ӏ came upon jᥙst what I needed.

I moѕt certainly will make sure to do not overlook
this website and give it a glance regularly.

helmsman · January 15, 2021 at 3:17 PM

hі!,I really ⅼіke yօur writing very much! share we keep up a correspondence extra appr᧐ximately your post
on AOL? I rеquіre an expert on this house to resolve my problem.
Maу be that’s you! Looкing forward to lоok you.

Pianino MultiLanguage · February 6, 2021 at 1:27 AM

Im totally confused after reading information on this site, and other websites and blogs. Which supplement, or nutritional supplements, should you actually be taking? One site says x is good for you, the other says it wastes your muscles, dont listen to them. Can anyone sort through the marketing hype and deliver actual honest feedback on good supplements to use?

Pianino TBF Kalisz · February 7, 2021 at 12:07 PM

Good being visiting your site again, its been months for me. This write-up that ive been waited for so lengthy. Id like this write-up to accomplish my assignment within the college, and it has exact same subject with your post. Thanks, great share.

Japan.M106.COM · February 12, 2021 at 10:32 PM

This waspretty beneficial material. Without a dobut I think this is well worth a bookmark, thanks

Norwegia XMC · February 16, 2021 at 12:54 AM

Majatek niektorych przekracza wartosc do ktorej potrafia liczyc. Mysla o zemscie zamiast umysl Cwiczyc…

Filozofia · February 19, 2021 at 12:09 PM

I admire the valuable information and facts you offer inside your posts. Ill bookmark your weblog and also have my children examine up right here typically. Im fairly positive theyll discover a lot of new things here than anybody else!

USA Charakterystyka · February 22, 2021 at 11:38 PM

My brother suggested I might like this blog. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

Cukrzyca · March 1, 2021 at 7:40 AM

I just got out of nap and I am already reading your articles. This signifies something! Very useful info. Thank you!

Leave a Reply

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

STAY CONNECT WITH US