Home/Blog/Programming/What is a Tuple in Python?
Home/Blog/Programming/What is a Tuple in Python?

What is a Tuple in Python?

10 min read
Jun 20, 2023

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Data types in Python#

In Python, tuples are one of the four built-in data types used to store collections of data. The other three built-in data types for this purpose include lists, sets, and dictionaries. Each data type has its own unique features and use cases.

Representation of a list, a tuple, and a set
Representation of a list, a tuple, and a set

Lists are mutable and ordered sequences of elements and are typically used for storing homogeneous data types, although they can also contain elements of different data types.

my_list = [1, 2, 3, 4, 5]
print(my_list)

Sets are mutable and unordered collections of unique elements and are useful for performing mathematical operations on data.

my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)

When the code above is run, the second occurrence of "apple" in the set is ignored, as sets only store unique elements.

Dictionaries are mutable and unordered collections of key-value pairs and are used for mapping keys to values, similar to a real-world dictionary.

my_dict = {"Alice": 25, "Bob": 30, "Charlie": 35}
print(my_dict)

Tuples are immutable and ordered sequences of elements and are useful for storing and passing around related pieces of data that should not be changed after creation.

my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

When creating a tuple with multiple elements, parentheses may not be used. However, these are often included for clarity.

my_tuple = 1, 2, 3
print(my_tuple)

What is a tuple?#

As described above, a tuple is an ordered and immutable sequence of elements, meaning that once created, the elements in a tuple cannot be modified.

The code below creates a tuple:

my_tuple = (1, 2, 3, 'four', 5.0)

In this example, my_tuple is a tuple that contains five elements. Note that the elements in a tuple can be of different types. For example, in the example above, there are three integer values, one string and one floating point (or double) value.

Accessing an element within a tuple is quite straightforward. Individual elements can be accessed by indexing them, similar to what is done in a list.

print(my_tuple[0]) # outputs 1
print(my_tuple[3]) # outputs 'four'

Multiple elements of a tuple can be accessed at a single time by using slicing.

print(my_tuple[1:3]) # outputs (2, 3)

In the code widget above, try to get elements out of range. For example, try to access the element at index 6. Does it throw an error? Try and find out!

One of the main benefits of using tuples over lists is that they are more memory-efficient and faster to iterate through. This makes them a good choice when you have a fixed set of values that we don't need to modify.

However, since tuples are immutable, no modification of elements can be done once they are created. Therefore, if there is a task where a collection of elements needs to be modified, lists will have to be used instead of tuples.

Important functions#

Some examples of how to use the functions and methods for Python tuples are listed below:

  • len(tuple): Returns the length of a tuple.

my_tuple = (1, 2, 3, 'four', 5.0)
print(len(my_tuple)) # outputs 5
  • tuple(seq): Converts a sequence (e.g., a list or a string) into a tuple.

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # outputs (1, 2, 3)
my_string = 'hello'
my_tuple = tuple(my_string)
print(my_tuple) # outputs ('h', 'e', 'l', 'l', 'o')
  • tuple.count(value): Returns the number of times a specified value appears in a tuple.

my_tuple = (1, 2, 3, 2, 2, 'hello')
print(my_tuple.count(2)) # outputs 3
print(my_tuple.count('goodbye')) # outputs 0

Since the word goodbye does not exist in my_tuple, the output of the code is 0 for that particular statement (Line 3).

  • tuple.index(value): Returns the index of the first occurrence of a specified value in a tuple.

my_tuple = (1, 2, 3, 2, 2, 'hello')
print(my_tuple.index(2)) # outputs 1
print(my_tuple.index('hello')) # outputs 5
#print(my_tuple.index(4)) # will throw an error

Note that if search is performed for a value that is not present in my_tuple, it will throw an error that says, "x not in tuple". You can see that after uncommenting the last line of the code.

  • The max(tuple) and min(tuple) functions return the maximum and minimum values in a tuple respectively. If the tuple contains all strings, the min(tuple) function will return the string occurring first in the alphabetical order, whereas the max(tuple) will return the string occurring last in the alphabetical order. Finally, if the tuple contains both numbers and strings, both the max(tuple) and min(tuple) functions will throw an error.

my_tuple = (1, 2, 3, 4, 5)
print(max(my_tuple)) # outputs 5
print(min(my_tuple)) # outputs 1
alphabetical_tuple = ("apple", "banana", "giraffe", "fox", "eel")
print(max(alphabetical_tuple)) # outputs giraffe
print(min(alphabetical_tuple)) # outputs apple
alphanumeric_tuple = (1, "apple", 2, "dog")
#print(max(alphanumeric_tuple)) # error
#print(min(alphanumeric_tuple)) # error
  • sorted(tuple): Returns a new sorted list from the elements in a tuple.

my_tuple = (3, 1, 4, 1, 5, 9, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # outputs [1, 1, 2, 3, 4, 5, 9]
  • any(tuple): Returns True if any element in a tuple is true, otherwise it will return False.

Note: In Python, many values can be evaluated as True or False.

  • True and False are boolean literals and evaluate to True and False respectively.
  • The integers 0 and 1 evaluate to False and True respectively.
  • An empty string "" evaluates to False, while any non-empty string evaluates to True.
  • An empty tuple () or list [] evaluates to False, while any non-empty tuple or list evaluates to True.
  • None evaluates to False.

  • So a tuple, such as (0, False, "", None), any() will return False because all of the elements in the tuple evaluate to False. However, tuples, such as (1, True, "hello") or any() will return True because at least one element in the tuple is True.

    my_tuple1 = (False, 0, None, '', ())
    my_tuple2 = (False, 0, None, '', (), True)
    print(any(my_tuple1)) # outputs False
    print(any(my_tuple2)) # outputs True
    • all(tuple): Returns True if all elements in the tuple are true, otherwise the function returns False. Note that an empty string is considered to be False.

    my_tuple1 = (True, 1, 'hello', [1, 2, 3])
    my_tuple2 = (True, 1, '', [1, 2, 3])
    print(all(my_tuple1)) # outputs True
    print(all(my_tuple2)) # outputs False
    • Tuple addition is used to concatenate two or more tuples into a single tuple.

    tuple1 = (1, 2, 3)
    tuple2 = (4, 5, 6)
    tuple3 = tuple1 + tuple2
    print(tuple3) #outputs (1, 2, 3, 4, 5, 6)
    • Tuple multiplication is used to create a new tuple by repeating the elements of an existing tuple a certain number of times.

    my_tuple = ("apple", "banana")
    new_tuple = my_tuple * 3
    print(new_tuple) # outputs ('apple', 'banana', 'apple', 'banana', 'apple', 'banana')

    In the example above, a tuple my_tuple, is defined containing two strings. The * operator is then used to create a new tuple new_tuple by repeating my_tuple three times.

    Note that the tuple1 + tuple2, and tuple1 * n examples provided earlier are simply expressions that combine or slicing tuples and do not require any additional functions or methods to use.

    Packing and unpacking a tuple#

    Packing refers to combining a sequence of values into a single tuple. This is done by placing the values inside parentheses separated by commas.

    my_tuple = (1, 2, 'three')

    Here, the values 1, 2, and 'three' are packed into a tuple and assigned to the variable my_tuple.

    On the other hand, unpacking refers to extracting values from a tuple and assigning them to separate variables. This can be done by using multiple variable names on the left-hand side of an assignment operator, separated by commas, and assigning a tuple to them. In the previous code, some values were assigned to my_tuple. In this code, my_tuple is unpacked and those values are assigned to variables a, b, and c respectively.

    a, b, c = my_tuple
    print(a) #outputs 1
    print(b) #outputs 2
    print(c) #outputs 'three'

    What happens to the code above, if for example, only a and b is used to unpack the values of my_tuple? Recall that my_tuple has three elements. If this is tried, it will throw an error, ValueError: too many values to unpack (expected 2). Try it yourself in the above code. Also see what happens if a, b, c and d are used.

    Packing and Unpacking
    Packing and Unpacking

    Nested tuples#

    Nested tuples are tuples that contain other tuples as elements.

    To create a nested tuple, simply include one or more tuples inside another tuple, separated by commas:

    my_tuple = ((1, 2), (3, 4), (5, 6))

    In the example provided above, my_tuple is a tuple that contains three tuples as its elements. Each of the inner tuples contains two integers.

    To access the elements of a nested tuple, indexing or nested indexing can be used.

    print(my_tuple[0]) # outputs (1, 2)
    print(my_tuple[1][0]) # outputs 3
    print(my_tuple[2][1]) # outputs 6

    In the first print statement, the first element of my_tuple is printed, which is the tuple (1, 2). In the second statement, nested indexing is used to access the first element of the second tuple, which is 3. In the third statement, nested indexing is again used to access the second element of the third tuple, which is 6.

    Tuples as keys in a dictionary#

    Tuples can also be used as keys in a dictionary. Since tuples are immutable and cannot be changed after they are created, they can be used as a reliable and unchanging key in a dictionary.

    In the example below, a dictionary is created with tuples as keys:

    my_dict = {('apple', 1): 'red', ('banana', 2): 'yellow', ('orange', 3): 'orange'}

    In this example, the keys are tuples containing a fruit and a number. The values are strings representing the colors of the fruits.

    The values in the dictionary can be accessed using the tuples as keys:

    print(my_dict[('apple', 1)]) # outputs 'red'
    print(my_dict[('banana', 2)]) # outputs 'yellow'
    print(my_dict[('orange', 3)]) # outputs 'orange'

    Advantages of tuples#

    Tuples have several advantages over other data types in Python, including:

    • Immutability: Tuples are immutable, meaning their contents cannot be modified after creation. This makes tuples more secure and less error-prone than mutable data types like lists, because they cannot accidentally be modified by other parts of the program.

    Tuples are immutable
    Tuples are immutable
    • Ordered: Tuples are ordered collections of elements which are useful if related pieces of data are stored that need to be accessed in a specific order.

    • Better performance: Tuples are faster than lists in terms of performance, as they require less memory and can be optimized by the Python interpreter.

    • Valid keys in dictionaries: Tuples are valid keys in dictionaries, while lists are not. Therefore, tuples as dictionary keys can be used if the intention is to create a dictionary that maps related pieces of data to each other.

    • Function returns: Tuples are often used to return multiple values from a function, as they can contain any number of elements and are easy to unpack. Following example returns multiple values packed in a tuple called return_tuple.

    def calculate_statistics(numbers):
    n = len(numbers)
    total = sum(numbers)
    mean = total / n
    variance = sum((x - mean) ** 2 for x in numbers) / n
    stdev = variance ** 0.5
    return_tuple = (total, mean, stdev)
    return return_tuple
    my_numbers = [1, 2, 3, 4, 5]
    total, mean, stdev = calculate_statistics(my_numbers)
    print("Total:", total)
    print("Mean:", mean)
    print("Standard deviation:", stdev)

    Disadvantages of tuples#

    Although tuples have several advantages over other data types in Python, they also have a few disadvantages. Some of them are listed below:

    • Immutability: While immutability can be an advantage, it can also be a disadvantage in some cases. Since tuples cannot be modified, a new tuple must be created if changes are required. This can be time consuming and may lead to more memory usage if you need to create many new tuples.

      • Limited functionality: Tuples have limited functionality compared to other data types like lists. For example, tuples do not have methods like append(), insert(), or remove(), which are available for lists.

    • Not suitable for large datasets: Tuples are not suitable for large data sets, as they are stored in memory and can consume a lot of memory if they contain a large number of elements. In such cases, other data types like arrays or generators may be more appropriate.

    Not suitable for large data sets
    Not suitable for large data sets
    • Limited readability: In some cases, tuples can be harder to read than other data types like lists, especially if the tuple contains many elements. This is because tuples are usually written with parentheses and commas, which can be visually confusing for some programmers.

    Conclusion and key takeaways#

    Tuples are an important data type in Python that allows us to store and manipulate collections of values. In this blog, we’ve covered the basics of creating and accessing tuples, tuple packing and unpacking, nested tuples, and using tuples as keys in dictionaries.

    Some key takeaways to keep in mind are:

    • Tuples are immutable.

    • Individual elements of a tuple using indexing can be accessed, just like with lists.

    • Tuples can be used as keys in dictionaries, making them a powerful tool for data manipulation.

    • Tuple packing allows us to group multiple values together into a single tuple.

    • Tuple unpacking allows us to assign multiple variables at once from a tuple.

    • Nested tuples can be used to represent more complex data structures.

    To learn more about tuples and other data structures commonly used in Python, we recommend a beginner's course on Python on our platform.

    Python 101

    Cover
    Python 101: Interactively learn how to program with Python 3

    Welcome to Python 101! I created this course to help you learn Python 3. My objective is to get you acquainted with the building blocks of Python so that you can write something useful yourself. With interactive playgrounds to help you learn right away, I will endeavor to not only get you up to speed on the basics, but also to show you how to create useful programs. This course will be split into five parts: Part-I covers Python's basics. Part-II is a small subset of Python's Standard Library. Part-III is intermediate material. Part-IV is a series of small tutorials. Part-V covers Python packaging and distribution.

    10hrs
    Beginner
    222 Playgrounds
    16 Illustrations

    Written By:
    Kamran Lodhi
     
    Join 2.5 million developers at
    Explore the catalog

    Free Resources