Oct 20, 2023 7 min read

Python Tuples

Learn about Python Tuples with our step-by-step tutorial. Python Tuple is an ordered collection of elements, enclosed in parentheses.

Python Tuples
Table of Contents

Introduction

Before we learn about python tuples, let's briefly understand-What are tuples ?

A tuple is an ordered collection of elements, enclosed in parentheses. It can contain items of different data types, and once created, its elements cannot be changed.

Tuples are versatile data structures that may be used to hold collections of either homogeneous or heterogeneous items.

In this tutorial, we’ll show you how to create a tuple, access elements, unpack a tuple, and more. We will also address a few FAQs on Python Tuples.

Creating Tuples

Tuples are made up of three or more things separated by commas and enclosed in a pair of round brackets (). They are allowed an unlimited number of goods of varying sorts. As an example, consider the following:

colors = ('orange', 'white', 'green')

Items in a tuple may include different data types. Additionally, you may define nested tuples when one or more of its components are dictionaries, lists, or tuples:

my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))

An empty tuple is shown by round brackets with no components between them:

my_tuple = ()

You must include a comma after the element to construct a tuple with just one element:

my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)
Output

<class 'int'>
<class 'tuple'>

The tuple()   may also be used to create tuples:

colors_list = ['orange', 'white', 'green']
colors_typle = tuple(colors_list)
print(type(colors_typle))
Output

<class 'tuple'>

Utilizing the tuple packing functionality, which enables you to generate a tuple out of a series of comma-separated items, is another technique to construct a tuple:

directions = "North", "South", "East", "West"
print(type(directions))
Output

<class 'tuple'>

Accessing Tuple Elements

The index of a tuple item may be used to refer to it. The range of integer indexes is 0 to n-1, where n is the total number of items:

my_tuple = ["a", "b", "c", "d"]
             0    1    2    3

Indexes are provided in Python using square brackets:

my_tuple[index]

For instance, you would use tuple_name[2] to get the third member of the tuple:

directions = ("North", "South", "East", "West")
directions[2]
Output

'East'

An IndexError exception is triggered if you reference a nonexistent index:

Output

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Use many indexes to retrieve the elements in a nested tuple:

my_tuple[3][1]
Output

'bar'

Negative indexes may be used to access the tuple elements as well. The last item is designated as -1, the next final item as -2, and so on:

my_tuple = ("a", "b", "c", "d")
            -4   -3   -2   -1
directions = ("North", "South", "East", "West")
directions[-2]
Output

'East'

Slicing Tuples

The following syntax may be used in Python to slice a tuple and other sequential data types:

sequence[start:stop:step]
  • The extraction will begin at the specified index start. An offset from the end of the tuple is indicated by a negative index. If you leave this option out, index 0 will be used as the starting point for the slices.
  • As stop indicates the index before which extraction should terminate, the element at index stop will be omitted from the final result. An offset from the end of the tuple is indicated by a negative index. Slicing continues to the end of the tuple if the length of this argument is more than or equal to the length of the tuple.
  • The slicing step may be specified using the optional parameter step. If not otherwise indicated, it will be set to 1. When the value of the slice is negative, the items are taken in the opposite order.

When you slice a tuple, you get a new tuple with only the components you want.

In Python, the following forms are acceptable:

T[:] # copy whole tuple
T[start:] # slice the tuple starting from the element with index "start" to the end of the tuple.
T[:stop] # slice the tuple starting from the begging up to but not including the element with index "stop".
T[start:stop] #  slice the tuple starting from the element with index "start" up to but not including the element with index "stop".
stop"
T[::step] # slice the tuple with a stride of "step"

The example below shows how to slice a tuple beginning with the element with index 1 and ending without including the element with index 4:

vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]
Output

('Garlic', 'Celery', 'Carrots')

Unpacking Tuples

A Python feature called "sequence unpacking" enables you to assign sequence objects to variables. Here's an illustration:

colors = ('orange', 'white', 'green')
a, b, c = colors
print(a)
print(b)
print(c)

The variables on the left are given the values of the tuple members based on their positions:

Output

orange
white
green

As a general rule, while unpacking tuples, the number of variables on the left side must equal the number of tuple members. A ValueError exception will be thrown otherwise.

colors = ('orange', 'white', 'green')
a, b = colors
Output

ValueError: too many values to unpack (expected 2)

When a method or function returns a list of objects, unpacking is useful:

def square_area_circumference(side_lenght):
  return side_lenght * side_lenght, side_lenght * 4

area, circumference = square_area_circumference(5)

print(area)
print(circumference)
Output

25
20

Changing a Tuple

Tuples cannot be directly updated since they are immutable data structures. Tuples are immutable, therefore you can't modify or delete their components.

A TypeError exception is thrown whenever an attempt is made to modify a tuple's element.

colors = ("orange", "white", "green")
colors[1] = "blue"
Output

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

A mutable tuple's elements may have their components modified. If the tuple has a list as one of its members, for instance, you may update the list items as follows:

my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)
Output

(1, 2, [5, 4, 7])

Tuple Length

The total number of objects in a collection may be obtained using the len() method.

For determining a tuple's length, use the len() function with the tuple as its parameter.

len(L)

Here is an example:

colors = ("orange", "white", "green")
lenght = len(colors)
print(lenght)
Output

3

Iterating Through a Tuple

You may use the for loop to repeatedly traverse over each element in a tuple:

directions = ("North", "South", "East", "West")
for direction in directions:
  print(direction)
Output

North
South
East
West

There are a variety of options available for generating indexes. The most frequent options are to combine the range() and len() operations or to utilize the built-in enumerate() function.

The following code snippet illustrates how to get the index and value of a tuple element.

directions = ("North", "South", "East", "West")
for i in range(len(directions)):
  print("Index {} : Value {}".format(i, directions[i]))
Output

Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West

You may loop through a tuple more Pythonically by using the enumerate() method rather than the range(len(...)) pattern:

directions = ("North", "South", "East", "West")
for index, value in enumerate(directions): 
  print("Index {} : Value {}".format(index, value))
Output

Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West

Check if an Element Exists

You may use the in and not in operators to determine if an element is present in a tuple:

colors = ("orange", "white", "green")
print("orange" in colors)

The output will be either True or False:

Output

True

Here is another instance of the if statement in use:

colors = ("orange", "white", "green")
if "blue" not in colors:
  print("no")
else:
  print("yes")
Output

no

Tuple Methods

The following methods are accepted by the tuple object:

  • count(x) - gives the quantity "x" in the tuple's appearances.
  • index(x) - returns the location of an element's first appearance with the value "x."

An easy illustration of how to use the techniques is provided below:

my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))
Output

2
0

FAQs on Python Tuples

How do you create a tuple in Python? 

To create a tuple, enclose comma-separated values within parentheses. For example: my_tuple = (1, 2, 3)

Can a tuple contain different data types?

Yes, a tuple can contain elements of different data types. For example: my_tuple = (1, "hello", 3.14)

How do you access elements of a tuple?

Elements of a tuple can be accessed using indexing. For example: my_tuple[0] would retrieve the first element.

Can you modify elements of a tuple?

No, tuples are immutable, meaning their elements cannot be modified after creation. You need to create a new tuple to change its contents.

Can tuples be nested? 

Yes, tuples can be nested, allowing you to create more complex data structures. For example: nested_tuple = ((1, 2), ("a", "b"), (True, False))

What is tuple unpacking in Python? 

Tuple unpacking is a feature that allows assigning values from a tuple to multiple variables in a single statement. For example: a, b, c = my_tuple

When should I use a tuple instead of a list? 

Use tuples when you require an immutable collection of elements, or when you want to ensure the order of items remains intact. Lists, on the other hand, are mutable and better suited for situations where elements need to be modified.

Conclusion

Tuples are immutable object sequences in Python that cannot be modified after they have been generated.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.