Tuples in Python

Amit Dhanwani on March 14, 2023

Tuples in Python

Learn about tuples in python, how to create a Python tuple and much more.

Introduction

A tuple is a group of Python objects that resembles a list. A tuple is a collection of items that can be of any type and are indexed by integers.

Tuples are immutable sequences that are frequently used to hold collections of heterogeneous data.

In a single variable name, a tuple enables you to store a variety of distinct data items.

A tuple’s values are separated syntactically by commas. It is more typical to define a tuple by enclosing the list of values in parentheses, which is not mandatory. This makes it simpler to understand Python tuples.

Tuples give you a way to easily process complex data structures without requiring an additional variable.

Tuples are immutable, which means that once they are generated, they cannot be modified, which is the primary distinction between the two. They are therefore perfect for storing information that shouldn’t be changed, like database records.

Any number of things, such as a text, integer, float, list, etc., may be included in a tuple.

Creating a Python tuple

A series of values separated by “a comma” is used to form tuples in Python. There are several ways to make tuples. The most typical method is to enclose them in parentheses. Both single and multiple tuples must always be separated by a comma.

Creating a tuple with the use of integers

Example:

Tuple1 = (0, 1, 2, 3)
print("\nTuple is:", Tuple1)

Tuple is: (0, 1, 2, 3)

We can also make a tuple without using parenthesis by separating the values with commas.

Tuple packing in Python is the process of creating a tuple without using parentheses.

Example:

Tuple1 = 0, 1, 2, 3
print("\nTuple packing  is:", Tuple1)

Tuple packing  is: (0, 1, 2, 3)

 

It’s advisable to continue using parentheses since this can easily become confusing.

 

Creating an empty tuple

Example:

Tuple1 = ()
print("\nEmpty Tuple is:", Tuple1)

Empty Tuple is: ()

 

Creating a tuple with the use of string

Example:

Tuple1 = ('Codingal', 'kids')
print("\n Tuple is:", Tuple1)

Tuple is: ('Codingal', 'kids')

 

Creating a tuple with a single item

The same thing can lead to issues if we just use one element.

Example:

Tuple1 = (1)
print(type(Tuple1))
print("\n Tuple is:", Tuple1)

<class 'int'>

Tuple is: 1

Tuple 1 is not a tuple, as can be seen; instead, it is treated as an int, which is an issue.

The solution is to follow the item with a comma.

Example:

Tuple1 = (1,)
print(type(Tuple1))
print("\n Tuple is:", Tuple1)

<class 'tuple'>

Tuple is: (1,)

This also applies to tuple packing, where we have to remove the parenthesis.

Example:

Tuple1 = 1,
print(type(Tuple1))
print("\n Tuple is:", Tuple1)

<class 'tuple'>

Tuple is: (1,)

 

Creating a tuple with the use of the list

We can create the tuple using the list, as shown below:

Example:

Tuple1 = [0, 1, 2, 3]
print(type(Tuple1))
print("\nTuple 1 is:", tuple(Tuple1))

<class 'list'>

Tuple 1 is: (0, 1, 2, 3)

Although the data type is a list in the example above, we are still getting a tuple as the result.

 

Creating a tuple with the use of a built-in function

Example:

Tuple1 = tuple("codingal")
print(type(Tuple1))
print("\nTuple 1 is:", Tuple1)

<class 'tuple'>

Tuple 1 is: ('c', 'o', 'd', 'i', 'n', 'g', 'a', 'l')

 

Creating a tuple with mixed data types

Tuples may have any number of items and any form of data (like strings, integers, list, etc.)

Example:

Tuple1 = ("codingal",2020,"kids",2023)
print(type(Tuple1))
print("\nTuple 1 is:", Tuple1)

<class 'tuple'>

Tuple 1 is: ('codingal', 2020, 'kids', 2023)

 

Creating a tuple with nested tuples

Example:

Tuple1 = ("codingal","kids")
Tuple2 = (2020,2023)
Tuple3 = (Tuple1, Tuple2)
print(type(Tuple3))
print("\nTuple 1 is:", Tuple3)

<class 'tuple'>

Tuple 1 is: (('codingal', 'kids'), (2020, 2023))

 

Creating a tuple with repetition

Example:

Tuple1 = ("codingal",)*3
print(type(Tuple1))
print(Tuple1)

<class 'tuple'>

('codingal', 'codingal', 'codingal')

 

Creating a tuple with the use of a loop

Example:

Tuple1 = ("codingal")
n=5
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)

('codingal',)

(('codingal',),)

((('codingal',),),)

(((('codingal',),),),)

((((('codingal',),),),),)

 

Accessing of tuples

Simply type a tuple’s name to access the items in Python tuples.

Example:

Tuple1 = (0, 1, 2, 3)
print("\nTuple 1 is:", Tuple1)

Tuple 1 is: (0, 1, 2, 3)

 

Accessing tuple with indexing

Example:

Tuple1 = (2020, 2021, 2022, 2023)
print("\nThe third item of Tuple 1 is:", Tuple1[2])

The third item of Tuple 1 is: 2022

When unpacking a tuple, the left-hand side variables should match the number of values in the provided tuple.

Example:

Tuple1 = 2020,2021,2022,2023
print("\nTuple packing  is:", Tuple1)
a, b, c, d = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
print(d)

Tuple packing  is: (2020, 2021, 2022, 2023)

Values after unpacking:

2020

2021

2022

2023

 

Slicing

 To retrieve a specified range or slice of sub-elements from a Tuple, slicing is used. Lists and arrays can also be divided via slicing.

While slicing allows for the retrieval of a collection of items, indexing in a list only allows for the retrieval of a single element.

The syntax is

name_of_tuple[start_index:end_index:step]

The start_index is the slice’s starting index; the element at this index will be included in the result; the default value is 0.

The end_index is the slice’s end index; the element at this index will not be included in the result. The default value is the len(sequence).

The step determines how much the index increases; its initial value is 1. If we give the step a negative number, we’ll move backward.

When working with positive indices, we move leftward through the list.

Example: In this example, the step size will be default value i.e 1.

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[3:5])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2023, 'codingal')

 

Example: In this example, the step size will be 2.

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[1:6:2])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2021, 2023, 'coding')

 

Different forms of indices

  • From the first item through the item at index 5, everything is printed out.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[:5])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2020, 2021, 2022, 2023, 'codingal')

 

  • This prints items from index 3 to the end of the list.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[3:])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2023, 'codingal', 'coding', 'kids')

 

  • This generates a Python tuple that is empty.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[3:3])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is ()

Considering negative indexing, it starts its traversal from the right, unlike positive indexing.

The order of the tuples can also be reversed by using negative increment values.

Examples:

  • This prints out the first 4 items of the tuple, starting at the beginning.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[:-3])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2020, 2021, 2022, 2023)

 

  • This prints out items starting at the end and going forward by 3 items.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[-3:])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is ('codingal', 'coding', 'kids')

 

  • This prints out everything from index 3 to the last two items.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[3:-2])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2023, 'codingal')

 

  • It will produce a tuple that is empty. This is because, in this example, the start(-3) comes after the end(3).
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[-3:3])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is ()

 

  • It prints the whole Python tuple when no indices are provided.
Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nTuple is:", Tuple1)
print("\nSlicing of tuple is",Tuple1[:])

Tuple is: (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

Slicing of tuple is (2020, 2021, 2022, 2023, 'codingal', 'coding', 'kids')

 

Deleting a tuple

Tuples cannot have any of their elements deleted since they are immutable. Using the del() function deletes the whole tuple.

An error is produced while printing a tuple that has been deleted.

Example:

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
del Tuple1
print("\nTuple is:", Tuple1)

Traceback (most recent call last):

File "main.py", line 3, in <module>

print("\nTuple is:", Tuple1)

NameError: name 'Tuple1' is not defined

 

Reassigning tuples in Python

Since a Python tuple is immutable, its values cannot be changed.

Example:

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
Tuple1[3] = 2024
print("\nTuple is:", Tuple1)

Traceback (most recent call last):

File "main.py", line 2, in <module>

Tuple1[3] = 2024

TypeError: 'tuple' object does not support item assignment

 

Python tuple built-in functions

A function performs an operation on a construct and outputs the result. It keeps the construct the same.

  • len():

Python tuples have a specific length. The tuple’s size or length is returned by the len() method.

Example:

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nLength of Tuple is:", len(Tuple1))

Length of Tuple is: 7

 

  • max():

The item from the tuple with the greatest value is returned.

Example on integers:

Tuple1 = (2020,2021,2022,2023)
print("\nMaximum value item of Tuple is:", max(Tuple1))

Maximum value item of Tuple is: 2023

Example on strings:

Tuple1 = ("codingal","coding","kids")
print("\nMaximum value item of Tuple is:", max(Tuple1))

Maximum value item of Tuple is: kids

Since k has the greatest ASCII value, it has been chosen as the result for strings where it depends on the ASCII value.

A string and an int, however, cannot be compared.

Example:

Tuple1 = (2020,2021,2022,2023,"codingal","coding","kids")
print("\nMaximum value item of Tuple is:", max(Tuple1))

Traceback (most recent call last):

File "main.py", line 2, in <module>

print("\nMaximum value item of Tuple is:", max(Tuple1))

TypeError: '>' not supported between instances of 'str' and 'int'

  • min ():

The min() method returns the item with the lowest values, comparable to the max() function.

Example:

Tuple1 = (2020,2021,2022,2023)
print("\nMinimum value item of Tuple is:", min(Tuple1))

Minimum value item of Tuple is: 2020

  • sum():

This method returns the tuple’s arithmetic sum for each item.

Example:

Tuple1 = (2020,2021,2022,2023)
print("\nSum of items value for Tuple is:", sum(Tuple1))

Sum of items value for Tuple is: 8086

This function, however, cannot be used on a tuple that contains strings.

Example:

Tuple1 = ("codingal","coding","kids")
print("\nSum of items value for Tuple is:", sum(Tuple1))

Traceback (most recent call last):

File "main.py", line 2, in <module>

print("\nSum of items value for Tuple is:", sum(Tuple1))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

  • any():

This method returns True if even one element in the tuple has a Boolean value of True. Otherwise, False is returned.

Example:

Tuple1 = ('0')
print(any(Tuple1))

True

The Boolean value of the string “0” is True. If rather the integer 0 had been used, False would have been returned.

Example:

Tuple1 = (0,)
print(any(Tuple1))

False

  • all():

In contrast to any(), all() only returns True if every item has a Boolean value of True. If not, it returns False.

Example 1:

Tuple1 = ('1','0','Codingal',6)
print(all(Tuple1))

True

Example 2:

Tuple1 = ('1','0','Codingal',6,False)
print(all(Tuple1))

False

Example 3:

Tuple1 = ('1','0','Codingal',6,'')
print(all(Tuple1))

False

  • sorted():

This method returns the tuple in sorted order. In Python, the sorting is done in ascending order without changing the original tuple.

Example:

Tuple1 = (2022,2023,2020,2021)
print(sorted(Tuple1))
  • tuple():

A different construct is transformed into a Python tuple via this function.

Example 1: List to tuple

List1 = [2022,2023,2020,2021]

print(tuple(List1))

(2022, 2023, 2020, 2021)

Example 2: String to tuple

str = "Codingal"
print(tuple(str))

('C', 'o', 'd', 'i', 'n', 'g', 'a', 'l')

Example 3: Set to tuple

set = {2020,2023,2021,2022}

print(tuple(set))

(2020, 2021, 2022, 2023)

We can observe that when a set was declared as 2020,2023,2021,2022, it ended up changing to 2020, 2021, 2022, and 2023. Additionally, it returned the new tuple in the new order, i.e. ascending order, when a Python tuple was created from it.

Python tuple methods

 A method is a set of instructions to carry out on a task. In contrast to a function, it alters the construct on which it is called. The dot operator is used in Python to invoke methods. Python tuples has two built-in methods.

  • index():

This function returns the index of an item’s first appearance in a tuple and only requires one parameter.

Example:

Tuple1 = (2020,2023,2021,2022,2023)
print("Index of 2023 in Tuple1 is:",Tuple1.index(2023))

Index of 2023 in Tuple1 is: 1

We have 2023 at indexes 1 and 4, as you can see. However, it just gives back the first index i.e 1.

  • count():

This function returns the number of times an item appears in the tuple using a single argument.

Example:

Tuple1 = (2020,2023,2021,2022,2023)
print("Count of 2023 in Tuple1 is:",Tuple1.count(2023))

Count of 2023 in Tuple1 is: 2

Python tuple operations

  • Membership

The operators “in” and “not in” can be used on items. This informs us if they are a part of the tuple.

Example 1:

Tuple1 = ("codingal","coding","kids")

print("Membership of codingal in Tuple1 is:",Tuple1 in tuple("codingal"))

Membership of codingal in Tuple1 is: False

Example 2:

Tuple1 = ("codingal","coding","kids")
print("Membership of codingal in Tuple1 is:",Tuple1 not in tuple("codingal"))

Membership of codingal in Tuple1 is: True

  • Concatenation:

The process of joining two or more Tuples is called concatenation. The “+” operator is used to concatenate.

Tuples are always joined at the end of the original tuple when concatenation is used.

On Tuples, other arithmetic operations are not applicable.

Example:

Tuple1 = ("codingal","coding","kids")
print("\nTuple1 is:",Tuple1)
Tuple2 = (2020,2023,2021,2022)
print("\nTuple2 is:",Tuple2)
print("\nConcatenation of Tuple1 & Tuple2 is:",Tuple1 + Tuple2)

Tuple1 is: ('codingal', 'coding', 'kids')

Tuple2 is: (2020, 2023, 2021, 2022)

Concatenation of Tuple1 & Tuple2 is: ('codingal', 'coding', 'kids', 2020, 2023, 2021, 2022)

Concatenation may only be used to combine the same datatypes; combining a list and a tuple result in an error.

Conclusion

The packing and unpacking of tuples in addition to how to make a tuple from a single item were discussed. Then we discussed accessing, slicing, deleting, and reassigning tuples.

The built-in functions and methods that we may call on a tuple were then discussed. Finally, we learnt about the operations a Python tuple may perform.

Tuples are immutable sequences that are frequently used to hold heterogeneous data sets. Tuples and lists vary primarily in that tuples are immutable whereas lists are mutable. If we just need to iterate through a collection of constant values, we use a tuple rather than a list.

Python is one of the popular and versatile programming languages. It is the best programming language to start with. Coding for kids has many beneficial advantages that develop cognitive abilities as well as enhances communication skills, entrepreneurship skills, and stimulates creativity.

Python is widely used in various fields such as data analysis, machine learning, software testing and prototyping, web development, and in many other areas.

Codingal offers Python for kids course to help your child enhance cognitive, logical, and computational skills. We provide 1:1 live interactive online coding classes for kids with expert coding instructors. Along with lifetime access to course content and downloadable learning resources, to cater to every child’s need by providing a personalized journey.

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class