"
This article is part of in the series

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)

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.