"
This article is part of in the series
Published: Saturday 31st July 2021
Last Updated: Saturday 28th May 2022

Learning about the built-in functions and data types in Python is one of the more significant leaps in knowledge you need to make before you're considered proficient in the language.

Tuples are one of the four built-in data types in Python, and understanding how it works shouldn't be too difficult.

Here's a breakdown of what tuples are, how they work, and how they are different from lists and dictionaries.

What is Tuple in Python?

As mentioned above, a tuple is one of the four data types that are built into Python. The other three data types are Lists, Sets, and Dictionaries. Every data type has its qualities and presents its unique drawbacks when used.

The characteristics of a Python tuple are:

  1. Tuples are ordered, indexed collections of data. Similar to string indices, the first value in the tuple will have the index [0], the second value [1], and so on. 
  2. Tuples can store duplicate values.
  3. Once data is assigned to a tuple, the values cannot be changed.
  4. Tuples allow you to store several data items in one variable. You can choose to store only one kind of data in a tuple or mix it up as needed.

How to Create and Use Tuples?

In Python, tuples are assigned by placing the values or "elements" of data inside round brackets "()." Commas must separate these items.

The official Python documentation states that placing items inside round parenthesis is optional and that programmers can declare tuples without using them. However, it is considered best practice to use round brackets when declaring a tuple since it makes the code easier to understand.

A tuple may have any number of values and the values can be of any type.

Here are some examples of declared tuples:

tuple1 = (1, 3, 5, 7, 9);
tuple2 = "W", "X", "c", "d";
tuple3 = ('bread', 'cheese', 1999, 2019);

You can also create an empty tuple by putting no values between the brackets, like so:

tuple1 = ();

Creating a tuple with just one value is a little tricky syntactically. When declaring a tuple with one value, you must include a comma entering the value before closing the bracket.

tuple1 = (1,);

This is for Python to understand that you are trying to make a tuple and not an integer or a string value.

Accessing Tuple Items 

In Python, you can access tuples in various ways. What's vital for you to remember is that Python tuple indices are like Python string indices – they are both indexed and start at 0.

Therefore, just like string indices, tuples can be concatenated, sliced, and so on. The three main ways of accessing tuples in Python are indexing, negative indexing, and slicing.

Method #1: Indexing

The index operator comes in handy when accessing tuples. To access a specific tuple in a tuple, you can use the "[]" operators. Bear in mind that indexing starts from 0 and not 1.

In other words, a tuple that has five values in it will have indices from 0 to 4. If you try to access an index outside of the existing range of the tuple, it will raise an "IndexError."

Further, using a float type or another type inside the index operator to access data in a tuple will raise a "TypeError."

Here’s an example of accessing a tuple using indexing:

tuple1 = (1, 3, 5, 7, 9);
print(tuple1[0])
# Output: 1

You can also put tuples inside of tuples. This is called nesting tuples. To access a value of a tuple that’s inside another tuple, you must chain the index operators, like so:

tuple1 = ((1, 3), (5, 7));
print(tuple1[0][1])
print(tuple1[1][0])
# Output: 
# 3
# 5

Method #2: Negative Indexing

Some languages do not allow negative indexing, but Python is not one of those languages. 

In other words, the index "-1" in tuples refers to the last item in the list, index "-2" refers to the second-last item, and so on.

Here's how you can use negative indexing to access tuple elements in Python:

tuple1 = (1, 3, 5, 7);
print(tuple1[-1])
print(tuple1[-2])
# Output: 
# 7
# 5

Method #3: Slicing

Accessing tuple values via slicing means accessing the elements using the slicing operator, which is the colon (":"). 

Here’s how slicing works:

tuple1 = ('p','y','t','h','o','n');

# To print second to fourth elements
print(tuple1[1:4])
# Output: ('y','t','h')

# To print elements from the beginning to the second value
print(tuple1[:-4])
# Output: ('p','y')

# To print elements from the fourth element to the end
print(tuple1[3:])
# Output: ('h','o','n')

# To print all elements from the beginning of the tuple to the end
print(tuple1[:])
# Output: ('p','y','t','h','o','n')

Slicing is an effective method of accessing the values in tuples. Visualizing the elements in the tuple, as shown below, can make it easier for you to understand the range and write the proper logic in the code.

Reference in python slicing = elements in the tuple

Altering Tuples

While Python lists are mutable, tuples are not. It is one of the primary characteristics of tuples – once the tuple elements are declared, they cannot be changed.

Here’s an example:

tuple1 = (1,2,3,4,5)

tuple1[0] = 7

# Output: TypeError: 'tuple' object does not support item assignment

However, tuples can store mutable elements such as lists in them. If the element stored is mutable, you can change the values nested in the element. Here's an example to demonstrate:

tuple1 = (1,2,3,[4,5])

tuple1[3][0] = 7

print(tuple1) 

# Output: (1,2,3,[7,5])

While the element's value cannot be changed once assigned, the tuple can be reassigned completely.

tuple1 = (1,2,3,[4,5])

tuple1 = ('p','y','t','h','o','n');

print(tuple1) 

# Output: ('p','y','t','h','o','n')

The only way that a tuple can be altered is through concatenation. Concatenation is the process of combining two or more tuples. Tuples can be concatenated using the + and the * operators.

# Concatenation using + operator

tuple1 = (('p','y','t')+('h','o','n'));

print(tuple1) 

# Output: ('p','y','t','h','o','n')

# Concatenation using * operator

tuple2 = (("Repeat",)* 3)

print(tuple2)

# Output: ('Repeat', 'Repeat', 'Repeat')

Deleting Tuples

Python does not allow programmers to change elements in a tuple. That means you cannot delete individual items in a tuple.

However, it is possible to delete a tuple entirely using the keyword “del.”

tuple1 = ('p','y','t','h','o','n')

del tuple1[2]

# Output: TypeError: 'tuple' object doesn't support item deletion

del tuple1

print(tuple1)

# Output: NameError: name 'my_tuple' is not defined

Methods Usable with Tuples

There are two methods that supply additional functionality when using tuples. The two methods are the count method and the index method.

Here is an example demonstrating how you can use both of the methods:

tuple1 = ('p','y','t','h','o','n')

print(tuple1.count('y'))

# Output: 1
# Since there is only one 'y' in the tuple

print(tuple1.index('y'))

# Output: 1
# Since the index of 'y' is 1

Tuple Operations

Tuples work much like strings and respond to all of the general operations you can perform to them. However, when operations are performed on them, the result is a tuple and not a string. 

Besides concatenation and repetition, there are some other operations that programmers can perform on tuples.

For instance, you can check the length of a tuple:

tuple1 = ('p','y','t','h','o','n')

print(len(tuple1))

You can also compare the elements of tuples and extract the maximum and minimum values in the tuple:

tuple1 = (1,2,3,4,5)

tuple2 = (5,6,7,8,9)

tuple1[4] == tuple2[0]

# Output: True

print(max(tuple1))

# Output: 5

print(min(tuple1))

# Output: 1

It is also possible for you to check whether an item exists in a tuple using the "membership test." Here's an example of a membership test:

tuple1 = (1,2,3,4,5)

1 in tuple1

# Output: True

'1' in tuple1

# Output: False

7 in tuple1

# Output: False

You can use a for loop to iterate through the items in a tuple. For instance:

for name in ('Kathy', 'Jimmy'):
   print('Hello', name)

Similarities Between Lists and Tuples in Python

Tuples and lists are similar in a handful of different ways, we’ve discussed how in this section.

Storage 

One of the main ways that tuples and lists are similar is that you can store multiple items in one variable in both. Additionally, both tuples and lists can be empty.

The key difference between the two is syntactical: you must use round brackets to declare a tuple and square brackets to declare a list.

You can create an empty tuple by typing in a variable name and adding parenthesis at the end. Alternatively, you can use the tuple() constructor to create the tuple.

It’s important to remember that if you create a tuple using the constructor, you will need to use double parenthesis to indicate your intentions to Python correctly.

Further, if you’re making a tuple with one item, you will need to add a trailing comma after the item. Python will not recognize the code as a tuple if you forget to add the comma.

Lists also work in a similar way. You can create a list by typing in the desired list name and adding square brackets at its end. Alternatively, you can use the list() constructor to create the list.

While you may think you will need to add a trailing comma after adding an item to a list, this is not the case. Python will recognize that it’s a list without needing you to add a trailing comma. 

Generally, the items stored in lists and tuples are similar in nature and tend to be related to one another somehow.

If you’re creating a list or tuple with sequences of strings, integers, or Boolean values, all you need to do is separate them by a comma. But this is not to say that you cannot create lists and tuples with different data types in them.

Just make sure you use apostrophes when adding strings and capitalize the T and F in True and False when adding Boolean values. Also, note that you can add duplicate items in both lists and tuples. 

Unpacking

One other similarity between tuples and lists is that both support unpacking. Python will “pack” many values into a single variable when you create a list or tuple.

The idea of unpacking is that Python enables you to assign individual values to individual variables.

However, regardless of whether you’re working with lists or tuples, you must make sure that you create the same number of variables as the values inside the list or tuple. If you don’t do this, Python will throw an error.

Indexing

The final similarity between lists and tuples is that both are ordered collections of items. In other words, the order of storage of the data is unchangeable once set. 

The values in both tuples and lists can be accessed by referencing the index value of the data. In Python and also most other programming languages, indexes start at zero. Therefore, the first value in a list or tuple will have the index zero, the second item one, and so on.

Differences Between Lists and Tuples

Tuples and lists serve the same function – they enable you to store different kinds of data in them. However, there are some major differences between the two.

Syntactically, tuples have values inside round brackets. However, if you want to represent a list in Python, you must put the values in square brackets ("[]").

Another key difference is that while you can change the elements in a list after assigning them, the values cannot be changed in a tuple.

Tuples are allotted to a single block of memory, whereas lists use two memory blocks. For this reason, iterating on tuples is faster than iterating on lists.

How to Choose Between Tuples and Lists 

Since iterating on tuples is faster, if you're building a solution that requires more rapid iteration, choosing to use a tuple over a list is a good idea.

Furthermore, if the problem you're solving doesn't require the elements to be changed, using a tuple is ideal. However, if the items need to the altered, you will need to use a list.

You can learn about using lists in Python in our guide on Python lists.

Dictionaries: The Third Collection Type

The dictionary is another data type that also serves as a collection. However, unlike lists and tuples, dictionaries are hash tables of key-value pairs. 

Another key difference between the other data types and dictionaries is that dictionaries are unordered. In addition, dictionaries are mutable, meaning you can add, change, or delete the elements in them. To declare a dictionary object, you must use the curly brackets ("{}").

To learn to create and use dictionary objects, check out our How to Create a Dictionary in Python post.

Conclusion

Tuples are handy data types that can serve as a powerful tool for solving complex problems. And now that you've gone through this guide, you understand what they are and how they work.

Writing some code with tuples in it is all you need to do to cement your knowledge of this powerful built-in Python function.