Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
tuple
data-structure

Tuples in Python

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring