What is a Tuple in Python

turned-on gray laptop computer

A tuple can be used to store a group of values in Python. A tuple is an immutable collection. This means adding, removing, or updating values is not possible.

Use tuples if you want to create a group of values that will never change.

To create a tuple in Python, separate values by a comma.

For example:

numbers = 1, 2, 3, 4, 5

Accessing a value of a tuple works the same way as accessing the values of a list.

For example:

numbers = 1, 2, 3, 4, 5
first_number = numbers[0]

print(first_number)

Looping through a tuple also works the same way as looping through a list:

numbers = 1, 2, 3, 4, 5

for number in numbers:
    print(number)

There are a lot more important aspects related to tuples. Let’s go through them in more detail.

Understanding Tuples in Python

A tuple is one of the main data types of Python. It is an immutable and ordered collection of data. You cannot modify the items of the tuple after creating the tuple.

A tuple can store any type of data. It is also possible to store different types of data into the same tuple.

Let’s start by learning how to create a tuple first.

How to Create a Tuple in Python

In Python, a tuple is a comma-separated collection of items.

For example, let’s create a tuple:

pets = "Cat", "Dog", "Hamster"

Sometimes it is useful or even required to use parenthesis to create a tuple.

For example, let’s create another tuple with parenthesis around it:

animals = ("Pig", "Elephant", "Kangaroo")

Tuples are similar to lists. The main difference is you cannot modify a tuple once created. This brings us to an important point: Use tuples when dealing with data that is supposed to remain the same.

If you find yourself trying to modify a tuple in any way, you should use a list instead.

Tuple with Parenthesis in Python

For the most part, you do not need to use parenthesis around a tuple in Python. However, you can use parenthesis to separate the tuple from the surrounding code if necessary.

Also, if you have a function that takes a tuple as an argument, you need to use parenthesis. This is because otherwise, the function thinks you gave it n arguments, instead of a single argument that is a tuple of n values.

For example, let’s create a function that prints a 3D point represented by a tuple:

def show(coordinates):
    x, y, z = coordinates
    print(f"The point is at ({x}, {y}, {z})")

show((4, 2, 7))

Output:

The point is at (4, 2, 7)

If you called this function without parenthesis, the Python interpreter would think you are passing it 3 separate arguments:

show(4, 2, 7)

This results in the following error:

TypeError: show() takes 1 positional argument but 3 were given

This is why it is mandatory to use parenthesis with a tuple when calling a function.

How to Access Elements of a Tuple

Similar to lists, a tuple item has a unique index that starts from zero. To access an item at a specific index of a tuple, reference the item’s index. This works the exact same way as accessing list elements.

For example, let’s create a tuple of numbers and access the first number of it:

numbers = 1, 2, 3, 4, 5
first_number = numbers[0]

print(first_number)

Output:

1

Negative Indexing of Tuples

In addition to the regular index, each tuple item has a negative index associated with it. This makes it more convenient to access the tuple from the “other end”. This feature also works the same way for lists.

For example, to access the last element of a tuple, you can use the negative index:

numbers = 1, 2, 3, 4, 5
last_number = numbers[-1]

print(last_number)

And the output is the last number:

5

What Data Types Tuples Support in Python

Tuples support any kind of data. Also, you can store multiple different data types into the same tuple if you want.

For example, let’s create a bunch of tuples that store all sorts of data:

t1 = 1, 2, 3
t2 = "Cat", 2, 3, "Dog"
t3 = lambda x: x ** 2, print, "Something", 2.41

However, even if this is possible, this is not very practical. Usually, you want to create a tuple to store related values that should remain the same.

Tuple Slicing in Python

If you want to get a subset of the items of your tuple, specify a range of indexes and access the tuple with that range.

For example, let’s create a numbers tuple and access the first 3 numbers:

numbers = 1, 2, 3, 4, 5

part = numbers[0:3]
print(part)

Output:

(1, 2, 3)

You can also use negative indexing to get a range of values from a tuple.

For instance, let’s grab the last two numbers from a tuple:

numbers = 1, 2, 3, 4, 5

part = numbers[-2:]
print(part)

Output:

(4, 5)

How to Sort a Tuple in Python

Because a tuple is an immutable collection, you cannot directly sort it.

However, the built-in function sorted() can be called on a tuple. This creates a sorted version of the tuple as a list.

For example:

numbers = 7, 5, 2, 1, 3, 2, 10
numbers = sorted(numbers)

print(numbers)

Output:

[1, 2, 2, 3, 5, 7, 10]

You can convert the list back to a tuple by calling the tuple() function on it.

Keep in mind, if you want to sort a tuple, you should not be using a tuple in the first place. A tuple is not meant to be changed after being created.

Next, let’s take a look at how you can iterate over a tuple.

How to Loop Through a Tuple in Python

You can loop through a tuple in the same way you loop through a list in Python.

For example, let’s use a for loop to print out the items of a tuple:

numbers = 1, 2, 3, 4, 5

for number in numbers:
    print(number)

Output:

1
2
3
4
5

And of course, you can use a while loop too:

numbers = 1, 2, 3, 4, 5

i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1

Output:

1
2
3
4
5

How to Delete an Element in Tuple in Python

You cannot remove an element of a tuple directly. This is because a tuple is an immutable collection. In other words, it cannot be changed after creation.

If you want to remove a value from a tuple, why are you not using a list instead?

Anyway, if you really want to remove a value from a tuple:

  1. Convert the tuple into a list
  2. Remove the value
  3. Convert it back to a tuple

Here is an example of how to remove the first value from a tuple:

numbers = 1, 2, 3, 4, 5

# 1. Convert the tuple into a list
numbers_list = list(numbers)

# 2. Remove the first elemenet
numbers_list.pop(0)

# 3. Convert the list back into a tuple
numbers = tuple(numbers_list)

print(numbers)

How to Add an Element into a Tuple in Python

You cannot add an element into a tuple directly. This is because a tuple is an immutable collection. In other words, it cannot be changed after creation.

If you want to add a value into a tuple, why are you not using a list instead?

Anyway, if you want to add a new value into a tuple, you need to create a new tuple from the original and the new items. To do this:

  • Add parentheses around the new item with a trailing comma (to make it a tuple).
  • Concatenate the new tuple to the end of the original one to create a new one with the new value

For example:

numbers = 1, 2

# create a new tuple with new value and assign it to the original tuple
numbers = numbers + (3, )

print(numbers)

Output:

(1, 2, 3)

Tuples vs Lists in Python

In a nutshell, here are the key differences between a tuple and a list in Python:

ListTuple
MutableImmutable
Looping is time-consumingLooping is fast
Consumes more memoryConsumes less memory
Has a variety of built-in methodsDoes not have many built-in methods

Mutability

Tuples are an immutable collection of items. A list is a mutable collection of items. In other words, you can modify a list after creation. But you cannot modify a tuple after creation.

Tuples Are Faster than Lists in Python

Tuples are stored in a single block of memory. Because a tuple is immutable, there is no need for reserving extra space for new items, as there will never be one.

But for a list, this is not the case. A list is mutable, so it needs to reserve some extra space for the possible new elements.

Syntax Differences

As you already know, the syntax for creating a tuple is different from creating a list.

With a list, you need to use square brackets, whereas with tuples you do not need anything.

For example:

numbers_tuple = 1, 2, 3, 4, 5
numbers_list = [1, 2, 3, 4, 5]

Common Operations

A list supports all sorts of built-in operations, such as pushing or popping.

Because a tuple is an immutable collection, many of the operations that list support are not supported by a tuple.

For example, you can add and remove elements of a list with built-in methods pop and append:

numbers = [1, 2, 3]

numbers.pop(0)
numbers.append(4)

print(numbers)

Output:

[2, 3, 4]

But a tuple does not support these.

Conclusion

A tuple is an immutable collection of items. You cannot change the values of a tuple after creating one.

Using tuples is clever if you want to make sure a group of values stays the same.

To create a tuple, comma-separate a group of values.

For example:

numbers = 1, 2, 3, 4, 5

Accessing and looping through the values of a tuple works the same way as for lists:

numbers = 1, 2, 3

# Get the first number
first_number = numbers[0]


# Loop through the tuple and print its items
for number in numbers:
    print(number)

But because a tuple is immutable by nature, you cannot directly add, update, or remove values from it.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share this article with others:

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email

Learn these 10 tips to write professional code.

 

Make your coding life easier with these amazing command-line tools

 

Learn how to use latest advancements in AI to write faster.

 

Leave a Comment

Your email address will not be published.