SlideShare a Scribd company logo
P
y
t
h
o
n
l
i
f
e
.
i
n
1
website:https://pythonlife.in/
Python Tuple
A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we
can change the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses(),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
my_tuple = ()
print(my_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [ ] to access an item in a tuple, where the index starts
from 0.So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
index outside of the tuple index range(6,7,... in this example) will raise an IndexError
The index must be an integer, so we cannot use float or other types. This will result in
TypeError.
P
y
t
h
o
n
l
i
f
e
.
i
n
2
website:https://pythonlife.in/
Likewise, nested tuples are accessed using nested indexing, as shown in the example
below.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1]) # 't'
print(my_tuple[-6]) # 'p'
In-built Functions for Tuple:
Function Description
cmp(tuple1,tuple2) Compares elements of two different tuples
len(tuple) Returns the length of the tuple
max(tuple) Returns the element with max value from the tuple
min(tuple) Returns the element with min value from the tuple
tuple(seq) Returns a tuple, by converting a list to a tuple. Takes a list in the
parameter
P
y
t
h
o
n
l
i
f
e
.
i
n
3
website:https://pythonlife.in/
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
print(my_tuple[:])
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need the index that will slice the portion from the
tuple.
P
y
t
h
o
n
l
i
f
e
.
i
n
4
website:https://pythonlife.in/
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned.
But, if the element is itself a mutable data type like a list, its nested items can be
changed.
We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
We can use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using the *
operator.
Both + and * operations result in a new tuple.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
P
y
t
h
o
n
l
i
f
e
.
i
n
5
website:https://pythonlife.in/
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we
cannot delete or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
Tuple Methods
Methods that add items or remove items are not available with
tuple. Only the following two methods are available.
Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
P
y
t
h
o
n
l
i
f
e
.
i
n
6
website:https://pythonlife.in/
Other Tuple Operations
1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword
in
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
2. Iterating Through a Tuple
We can use a for loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)
Advantages of Tuple
● Tuples being immutable, turns out to be a write-protected collection. Tuples can
be of advantage when we want to store some secure read-only data that we
cannot afford to be changed throughout our code.
● Tuples can store data of multiple data types, which makes them a heterogeneous
collection.
● Tuple being a read only collection, has a faster iteration. (As they are stored in a
single block of memory, and don’t have extra space for storing objects, they have
a constant set of values)
P
y
t
h
o
n
l
i
f
e
.
i
n
7
website:https://pythonlife.in/
Disadvantages of Tuple of Tuple
● Tuple’s being write protected, is an advantage but also a disadvantage as it
cannot be used when we want to add or delete a specific element. Hence has a
limited use case.
● Syntactically less readable as tuples can be created by either adding
parentheses or by not providing them in case we have more than one element.
But not using parentheses in the case of one element, will not create a tuple and
hence a trailing comma in such case is required. This can make code readability
a bit complex for some.
● As tuple is a class, it's stored on the heap and is overhead on the garbage
collector.

More Related Content

PPTX
Python Collections
PPTX
Effective tuples in phyton template.pptx
PPTX
1.10 Tuples_sets_usage_applications_advantages.pptx
PDF
computer science tuple in python project.pdf
PPTX
Tuples in python better understanding with slides
PDF
Tuple Operation and Tuple Assignment in Python.pdf
PPTX
Tuples in pyhton programming using simple codes.pptx
PDF
Python tuple
Python Collections
Effective tuples in phyton template.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx
computer science tuple in python project.pdf
Tuples in python better understanding with slides
Tuple Operation and Tuple Assignment in Python.pdf
Tuples in pyhton programming using simple codes.pptx
Python tuple

Similar to Tuple in Python class documnet pritened. (20)

PDF
Python Interview Questions And Answers
PPTX
tupple.pptx
PDF
Python revision tour II
PDF
Python Tuple.pdf
PPTX
Improve Your Edge on Machine Learning - Day 1.pptx
PDF
updated_tuple_in_python.pdf
PDF
Python-Tuples
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PPTX
Lecture 09.pptx
PDF
tuples chapter (1).pdfhsuenduneudhhsbhhd
PPTX
set.pptx
PPTX
Python Tuples.pptx
PPTX
Tuples.pptx
PPTX
Chapter 13 Tuples.pptx
PPTX
tuple in python is an impotant topic.pptx
PDF
justbasics.pdf
PPTX
Basic of Python- Hands on Session
PPTX
Chapter 13 Tuples.pptx
PPTX
Chapter 17 Tuples
PDF
advanced python for those who have beginner level experience with python
Python Interview Questions And Answers
tupple.pptx
Python revision tour II
Python Tuple.pdf
Improve Your Edge on Machine Learning - Day 1.pptx
updated_tuple_in_python.pdf
Python-Tuples
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Lecture 09.pptx
tuples chapter (1).pdfhsuenduneudhhsbhhd
set.pptx
Python Tuples.pptx
Tuples.pptx
Chapter 13 Tuples.pptx
tuple in python is an impotant topic.pptx
justbasics.pdf
Basic of Python- Hands on Session
Chapter 13 Tuples.pptx
Chapter 17 Tuples
advanced python for those who have beginner level experience with python
Ad

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Computing-Curriculum for Schools in Ghana
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Cell Types and Its function , kingdom of life
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
01-Introduction-to-Information-Management.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Institutional Correction lecture only . . .
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
master seminar digital applications in india
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Computing-Curriculum for Schools in Ghana
Module 4: Burden of Disease Tutorial Slides S2 2025
Cell Types and Its function , kingdom of life
102 student loan defaulters named and shamed – Is someone you know on the list?
Abdominal Access Techniques with Prof. Dr. R K Mishra
Renaissance Architecture: A Journey from Faith to Humanism
01-Introduction-to-Information-Management.pdf
VCE English Exam - Section C Student Revision Booklet
Basic Mud Logging Guide for educational purpose
Microbial diseases, their pathogenesis and prophylaxis
Institutional Correction lecture only . . .
PPH.pptx obstetrics and gynecology in nursing
TR - Agricultural Crops Production NC III.pdf
master seminar digital applications in india
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Insiders guide to clinical Medicine.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Ad

Tuple in Python class documnet pritened.

  • 1. P y t h o n l i f e . i n 1 website:https://pythonlife.in/ Python Tuple A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list. Creating a Tuple A tuple is created by placing all the items (elements) inside parentheses(), separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). my_tuple = () print(my_tuple) my_tuple = (1, 2, 3) print(my_tuple) my_tuple = (1, "Hello", 3.4) print(my_tuple) my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple) Access Tuple Elements There are various ways in which we can access the elements of a tuple. 1. Indexing We can use the index operator [ ] to access an item in a tuple, where the index starts from 0.So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError The index must be an integer, so we cannot use float or other types. This will result in TypeError.
  • 2. P y t h o n l i f e . i n 2 website:https://pythonlife.in/ Likewise, nested tuples are accessed using nested indexing, as shown in the example below. my_tuple = ('p','e','r','m','i','t') print(my_tuple[0]) # 'p' print(my_tuple[5]) # 't' n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested index print(n_tuple[0][3]) # 's' print(n_tuple[1][1]) # 4 2. Negative Indexing Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. my_tuple = ('p', 'e', 'r', 'm', 'i', 't') print(my_tuple[-1]) # 't' print(my_tuple[-6]) # 'p' In-built Functions for Tuple: Function Description cmp(tuple1,tuple2) Compares elements of two different tuples len(tuple) Returns the length of the tuple max(tuple) Returns the element with max value from the tuple min(tuple) Returns the element with min value from the tuple tuple(seq) Returns a tuple, by converting a list to a tuple. Takes a list in the parameter
  • 3. P y t h o n l i f e . i n 3 website:https://pythonlife.in/ 3. Slicing We can access a range of items in a tuple by using the slicing operator colon : my_tuple = ('p','r','o','g','r','a','m','i','z') print(my_tuple[1:4]) print(my_tuple[:-7]) print(my_tuple[7:]) print(my_tuple[:]) Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.
  • 4. P y t h o n l i f e . i n 4 website:https://pythonlife.in/ Changing a Tuple Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like a list, its nested items can be changed. We can also assign a tuple to different values (reassignment). my_tuple = (4, 2, 3, [6, 5]) my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5]) print(my_tuple) my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple) We can use + operator to combine two tuples. This is called concatenation. We can also repeat the elements in a tuple for a given number of times using the * operator. Both + and * operations result in a new tuple. # Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)
  • 5. P y t h o n l i f e . i n 5 website:https://pythonlife.in/ Deleting a Tuple As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple. Deleting a tuple entirely, however, is possible using the keyword del. # Deleting tuples my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # can't delete items # TypeError: 'tuple' object doesn't support item deletion # del my_tuple[3] # Can delete an entire tuple del my_tuple # NameError: name 'my_tuple' is not defined print(my_tuple) Tuple Methods Methods that add items or remove items are not available with tuple. Only the following two methods are available. Some examples of Python tuple methods: my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # Output: 2 print(my_tuple.index('l')) # Output: 3
  • 6. P y t h o n l i f e . i n 6 website:https://pythonlife.in/ Other Tuple Operations 1. Tuple Membership Test We can test if an item exists in a tuple or not, using the keyword in # Membership test in tuple my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation print('a' in my_tuple) print('b' in my_tuple) # Not in operation print('g' not in my_tuple) 2. Iterating Through a Tuple We can use a for loop to iterate through each item in a tuple. # Using a for loop to iterate through a tuple for name in ('John', 'Kate'): print("Hello", name) Advantages of Tuple ● Tuples being immutable, turns out to be a write-protected collection. Tuples can be of advantage when we want to store some secure read-only data that we cannot afford to be changed throughout our code. ● Tuples can store data of multiple data types, which makes them a heterogeneous collection. ● Tuple being a read only collection, has a faster iteration. (As they are stored in a single block of memory, and don’t have extra space for storing objects, they have a constant set of values)
  • 7. P y t h o n l i f e . i n 7 website:https://pythonlife.in/ Disadvantages of Tuple of Tuple ● Tuple’s being write protected, is an advantage but also a disadvantage as it cannot be used when we want to add or delete a specific element. Hence has a limited use case. ● Syntactically less readable as tuples can be created by either adding parentheses or by not providing them in case we have more than one element. But not using parentheses in the case of one element, will not create a tuple and hence a trailing comma in such case is required. This can make code readability a bit complex for some. ● As tuple is a class, it's stored on the heap and is overhead on the garbage collector.