Learning Python: Tuples

Tuples are another data structure available in Python. Tuples give us the ability to create objects that are immutable.

One of the differences between tuples and lists, are that Tuples use round brackets while lists use square brackets.

Examples

A simple tuple

name_dept = ("Peter", "Engineering")

We can access a tuple like a list using its index:

print(name_dept[0]) # "Peter"
print(name_dept[1]) # "Engineering"

OR

We can use the index() method:

print(name_dept.index('Peter')) # 0
print(name_dept.index('Engineering')) # 1

We can search tuples from the end like we can with lists:

name_dept[-1] # True

We can check if an element is in a tuple:

print("Peter" in name_dept) # True

We can get the length of a tuple using the len() method:

len(name_dept) # 2

Part of a tuple can be extracted by slicing:

name_dept[0:2] # ('Peter', 'Engineering')
name_dept[1:] # ('Engineering')

A new tuple can be created from an existing tuple:

tuple1 = name_dept + ("Kelly", "IT")

This blog post was originally published on my blog Communicode, where I write about different tech topics.

Python
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.