Trusted answers to developer questions

Tuples in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

What is a tuple?

A tuple is an immutable list of Python objects which means it can not be changed in any way once it has been created. Unlike sets, tuples are an ordered collection.

Creating a tuple

Now let’s take a look at an example of a tuple.

tupleExmp = ("alpha","bravo","charlie")
print(tupleExmp)

Once a tuple is created, items cannot be added or removed and their values cannot be changed. Changing the above tuple will generate an error.

tupleExmp = ("alpha","bravo","charlie")
tupleExmp[0] = "100" #changing the value at zeroth index

Accessing tuple items

Tuple indexes are zero-based, just like a list, so the first element of a non-empty tuple is always tuple[0].

Negative indexes count from the end of the tuple, just like a list.

tupleExmp = ("alpha","bravo","charlie")
print(tupleExmp[1])
print(tupleExmp[-1])

You can also loop through the tuple values using a for loop.

tupleExmp = ("alpha","bravo","charlie")
for item in tupleExmp:
print(item)

Length of a tuple

The length of a tuple can be found using the len() function.

tupleExmp = ("alpha","bravo","charlie")
print(len(tupleExmp))

RELATED TAGS

python
tuple
data-structure
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?