Software, Tech & Coding simplified.

What is a Tuple in Python?

turned-on gray laptop computer

In Pyhton, a tuple can be used to store a group of values.

A tuple is an immutable collection of values.

This means adding, removing, or updating values is not possible after creation.

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

Depending on the context, sometimes parenthesis is used around tuples.

For instance:

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)

In this guide, you learn everything you need to know about tuples in Python. The theory is backed up with great and demonstrative examples.

Understanding Tuples in Python

A tuple is one of the main data types in Python.

A tuple 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 possible to store different types of data into the same tuple.

To get started with tuples in Python, let’s first learn how to create one.

How to Create a Tuple in Python

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

Thus, to create a tuple, separate a group of values by commas.

For example, let’s create a tuple of animal names:

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

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

For example, let’s create the very same tuple with parenthesis around it:

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

Tuples are similar to lists when it comes to accessing elements.

But there are some key differences between lists and tuples.

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.

Next, let’s take a closer look at a situation in which you should use parenthesis when creating tuples in Python.

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.

To demonstrate, let’s create a function that prints a 3D point represented by a tuple and call it with a tuple of coordinates:

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

# Call the function with a tuple
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

The error says it all. You are trying to give the function 3 separate arguments, even though it only accepts one.

This is an example of a situation in which it is mandatory to use parenthesis with a tuple.

At this point, you know how to create a tuple with and without parenthesis.

Furthermore, you understand why sometimes it is necessary to use parenthesis around a tuple.

Next, let’s move on to dealing with tuples.

We are going to start by looking at how to access elements of a tuple.

How to Access Elements of a Tuple

When you store elements somewhere, you naturally want to be able to access them with ease.

If you have worked with lists before, you know that all you need to do is know the index of the element and use the square brackets operator:

items[0] # returns the first element in a list

Accessing tuple values is identical to this.

Similar to lists, each tuple item has a unique index that starts from zero.

To access an item at a specific index of a tuple, you need to know the item’s index.

This works the exact same way as accessing list elements.

  • Specify the index of the element.
  • Use square brackets operator and pass the index as an argument.

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

numbers = 1, 2, 3, 4, 5

# The first number is at index 0.
first_number = numbers[0]

print(first_number)

Output:

1

This is the most basic approach to accessing tuple elements.

However, tuples also support negative indexing, in which the index starts at -1 from the right-hand side.

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 in the tuple:

5

Now that you understand how to access tuple elements, let’s see what kinds of elements you can insert into a tuple.

What Data Types Tuples Support in Python

Tuples support any kind of data.

In other words, you can insert any Python object in a tuple.

Furthermore, you can store multiple different data types into the same tuple if you want.

For example:

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

Even though storing different types of data in the same tuple is possible, it is not practical.

Usually, you want to create a tuple to store related values that should remain the same.

Thus it can cause a lot of confusion if you store different types of data into the same tuple.

So stay away from it.

Now you understand the basics of tuples in Python.

Next, let’s go back to accessing tuple elements to see an ever so slightly more advanced use called slicing.

Tuple Slicing in Python

Slicing lets you access a subset of a tuple.

The slicing follows either one of these syntaxes:

[start:stop]
[start:stop:stepsize]

Where:

  • start specifies the starting index.
  • stop specifies the index of the last element in the range (excluding the end index).
  • stepsize is the number of steps to step over in the range.

To find a complete tutorial on slicing, feel free to read this comprehensive guide.

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)

Next, let’s move on to more common tasks related to tuples in Python.

How to Sort a Tuple in Python

Because a tuple is an immutable collection, you cannot 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

As you learned multiple times already, a tuple is an immutable collection of values.

Thus, you cannot remove an element of a tuple directly.

If you want to remove a value from a tuple you are using the wrong data type in the first place.

Use a list instead.

Anyway, if you really, 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)

But as you can see, this is not practical.

You should use a list instead.

How to Add an Element into a Tuple in Python

Because a tuple is an immutable collection, you cannot add elements to it.

If you find yourself in a situation where you wan to add elements to a tuple, you should use 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)

We have talked a lot about tuples thus far. You have also seen how they are somewhat closely related to Python lists.

Thus, this guide would be incomplete without more thorough tuples vs lists comparison.

Tuples vs Lists in Python

If there is one difference you need to know, it is mutability.

A tuple is immutable, that is, unchangeable.

A list is mutable, that is, changeable.

Here are some other key differences between lists and tuples 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

Let’s briefly discuss these differences to learn what they actually mean.

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.

You already saw a bunch of examples of these. For instance, you cannot add or remove elements from a tuple.

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.

This is what makes handling tuples slightly faster than lists.

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 (or you can use parenthesis if needed).

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

Today you learned what is a tuple in Python.

To recap, 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

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