alternative
  • Home (current)
  • About
  • Tutorial
    Technologies
    C#
    Deep Learning
    Statistics for AIML
    Natural Language Processing
    Machine Learning
    SQL -Structured Query Language
    Python
    Ethical Hacking
    Placement Preparation
    Quantitative Aptitude
    View All Tutorial
  • Quiz
    C#
    SQL -Structured Query Language
    Quantitative Aptitude
    Java
    View All Quiz Course
  • Q & A
    C#
    Quantitative Aptitude
    Java
    View All Q & A course
  • Programs
  • Articles
    Identity And Access Management
    Artificial Intelligence & Machine Learning Project
    How to publish your local website on github pages with a custom domain name?
    How to download and install Xampp on Window Operating System ?
    How To Download And Install MySql Workbench
    How to install Pycharm ?
    How to install Python ?
    How to download and install Visual Studio IDE taking an example of C# (C Sharp)
    View All Post
  • Tools
    Program Compiler
    Sql Compiler
    Replace Multiple Text
    Meta Data From Multiple Url
  • Contact
  • User
    Login
    Register

Python - Datatype - Tuple Tutorial

A tuple is used to store the sequence of various types of items like int, float, list, string, etc.

It is similar to a list, the only difference is tuple is immutable(i.e not modifiable), while the list is mutable (i.e modifiable)

It is stored under parenthesis (), here parentheses are optional and it is separated with commas.

We can use indexing to access an item of the tuple separately. Its indexing starts from 0 and ends at n-1. Where n is the total number of elements.

It supports both +ve and -ve indexing. It can contain duplicate values.

Trying to access another index that is not in the list will give IndexError. An index must be always an integer, otherwise, it will give TypeError.

Example-

# empty tuple
tuple_a = ()
print(tuple_a)

# Tuple of integers
tuple_b = (2, 9, 12)
print(tuple_b)

# Accessing the 1st element of the tuple_b
print(tuple_b[0])

# tuple with mixed data types
tuple_c = (1, "Hello", 1.02)
print(tuple_c)

# Accessing the last element of the tuple_c
print(tuple_c[2])

# tuple without parentheses
tuple_d = 2, 4.12 , 'Sam'
print(tuple_d)

Output-

()
(2, 9, 12)
2
(1, 'Hello', 1.02)
1.02
(2, 4.12, 'Sam')

 

A tuple is immutable, unlike a list. It means we cannot modify or change the value of the element in the tuple after it is created. Otherwise, it will give TypeError.

But we can modify the mutable item (e.g List) in the tuple.

Example-

# tuple of integers
tuple_b = (2, 9, 12, [21, 5])
print(tuple_b)

# Modifying the list in tuple
tuple_b[3][0] = 12
print(tuple_b)

# Modifying the 2nd element to a string
tuple_b[0]="String"
print(tuple_b)

Output-

(2, 9, 12, [21, 5])
(2, 9, 12, [12, 5])

Traceback (most recent call last):
  File "jdoodle.py", line 10, in <module>
    tuple_b[0]="String"
TypeError: 'tuple' object does not support item assignment

 

 

Tuples can also have another tuple as an item. This is called a nested tuple.

Example-

# Nested Tuple
tuple_b = (2, 9, ('Sam', 2.14, 5), ['fresherbell', 3.14])

# Accessing the nested tuple
# Accessing 1st item of tuple
print(tuple_b[1])

# Accessing 1st item of the 3rd item of tuple
print(tuple_b[2][0])

# Accessing 3rd item of the 3rd item of tuple
print(tuple_b[2][2])

# Accessing 2nd item of the list of the 3rd item of tuple
print(tuple_b[3][1])

 

Negative Indexing

In python, we can use negative indexing. Suppose we want to access the last element of the tuple and we are unaware of the number of the element in the tuple. In that case, we can use negative indexing to access the tuple element from the end.

The index of -1 refers to the last index, -2 refers to the second last index, and so on.

Example-

# tuple of integers
tuple_b = (2, 9, 12)
print(tuple_b)

# Accessing the last element of the tuple_b
print(tuple_b[-1])
print(tuple_b[-2])

Output-

(2, 9, 12)
12
9

 

Slicing tuple in python

We can get a particular range of items from a tuple using a colon (:)

Example-

# tuple
tuple_b = (2, 9, 12, "fresherbell", "python", "tutorial", 2.24, 21.3)

# Accessing the element 4th to 6th
print(tuple_b[3:6])

# Accessing the element from start to 3rd
print(tuple_b[:3])

# Accessing the element 5th to last
print(tuple_b[4:])

# Accessing the element  last 5th to last
print(tuple_b[-5:])

 

Output-

('fresherbell', 'python', 'tutorial')
(2, 9, 12)
('python', 'tutorial', 2.24, 21.3)
('fresherbell', 'python', 'tutorial', 2.24, 21.3)

 

Addition of element in the tuple (using concatenation & repetition)

A tuple is immutable. We cannot add, remove or modify the element in the tuple.

But we can concatenate two or more tuple

Concatenation or combining two lists using the + operator can also use the * operator to repeat the same tuple.

# tuple of integers
tuple_a = [2, 9, 12]

# tuple of string
tuple_b = ['fresherbell', 'python', 'tutorial']

# Adding two tuple or Concatenating
tuple_c = tuple_a + tuple_b
print(tuple_c)

# using * to repeat same tuple
print(tuple_a * 2)

Output-

[2, 9, 12, 'fresherbell', 'python', 'tutorial']
[2, 9, 12, 2, 9, 12]

 

Removal of the element from a tuple OR Deleting the tuple

We cannot remove one item or multiple items from a tuple using the del keyword.

But we can delete the whole tuple at a time.

Example 1-

# tuple
tuple_b = (18, 3, 4, 7, 12)

# delete the particular element(4th item) from tuple will give error
del tuple_b[3]
print(tuple_b)

Output-

Traceback (most recent call last):
  File "jdoodle.py", line 5, in <module>
    del tuple_b[3]
TypeError: 'tuple' object doesn't support item deletion

 

Example 2-

# tuple
tuple_a = (2, 9, 'fresherbell')

# deleting the whole tuple
del tuple_a
print(tuple_a)

Output-

Traceback (most recent call last):
  File "jdoodle.py", line 5, in <module>
    print(tuple_a)
NameError: name 'tuple_a' is not defined

 

Tuple Packing

Assigning multiple values to a single variable

a=(1,2,3,True,"abc")
print(a)

Output-

(1, 2, 3, True, 'abc')

 

Tuple Unpacking

Assigning multiple values to multiple variables

a,b,c,d,e=(1,2,3,True,"abc")
print(a)
print(c)
print(e)

Output-

1
3
abc

 

Index()

To get the index of a particular item in a tuple, we will use the index() method.

Syntax of index() method-

tuple.index(element, start position, end position)

Start and end positions are optional.

If no element is found in the tuple, It will raise a ValueError exception.

It will return the only first occurrence of an element.

# tuple
tuple_a = (2, 9, 2, 8, 2, 18, 19, 20, 2)

# To get the index of 2
i = tuple_a.index(2)
print(i)

# To get the index of 2, from position 3 to 7
i = tuple_a.index(2,3,7)
print(i)

# To get the index of 49
i = tuple_a.index(49)
print(i)

Output-

0
4
Traceback (most recent call last):
  File "jdoodle.py", line 13, in <module>
    i = tuple_a.index(49)
ValueError: tuple.index(x): x not in tuple

 

 

Count()

To count() the number of times the particular item is in the tuple. We will use the count() method.

Syntax-

tuple.count(element)

 

# tuple
tuple_a = (2, 9, 2, 8, 2, 18, 19, 20, 2)

# To get the count of 2
c = tuple_a.count(2)
print(c)

Output-

4

 

Iteration in a tuple

We can use for loop to iterate through a tuple.

# tuple
tuple_a = (2, 9, 2, 8, 2, 18, 19, 20, 2)

# To get the count of 2
for i in tuple_a:
    print("Value =", i)

 

Output-

Value = 2
Value = 9
Value = 2
Value = 8
Value = 2
Value = 18
Value = 19
Value = 20
Value = 2

 

Python

Python

  • Introduction
  • Installation and running a first python program
    • How to install Python ?
    • Running 1st Hello World Python Program
    • How to install Pycharm ?
  • Things to know before proceed
    • Escape Characters/Special Characters
    • Syntax ( Indentation, Comments )
    • Variable
    • Datatype
    • Keyword
    • Literals
    • Operator
    • Precedence & Associativity Of Operator
    • Identifiers
    • Ascii, Binary, Octal, Hexadecimal
    • TypeCasting
    • Input, Output Function and Formatting
  • Decision control and looping statement
    • if-else
    • for loop
    • While loop
    • Break Statement
    • Continue Statement
    • Pass Statement
  • Datatype
    • Number
    • List
    • Tuple
    • Dictionary
    • String
    • Set
    • None & Boolean
  • String Method
    • capitalize()
    • upper()
    • lower()
    • swapcase()
    • casefold()
    • count()
    • center()
    • endswith()
    • split()
    • rsplit()
    • title()
    • strip()
    • lstrip()
    • rstrip()
    • find()
    • index()
    • format()
    • encode()
    • expandtabs()
    • format_map()
    • join()
    • ljust()
    • rjust()
    • maketrans()
    • partition()
    • rpartition()
    • translate()
    • splitlines()
    • zfill()
    • isalpha()
    • isalnum()
    • isdecimal()
    • isdigit()
    • isidentifier()
    • islower()
    • isupper()
    • isnumeric()
    • isprintable()
    • isspace()
    • istitle()
  • Python Function
    • Introduction
  • Lambda Function
    • Lambda Function
  • Python Advanced
    • Iterators
    • Module
    • File Handling
    • Exceptional Handling
    • RegEx - Regular Expression
    • Numpy
    • Pandas

About Fresherbell

Best learning portal that provides you great learning experience of various technologies with modern compilation tools and technique

Important Links

Don't hesitate to give us a call or send us a contact form message

Terms & Conditions
Privacy Policy
Contact Us

Social Media

© Untitled. All rights reserved. Demo Images: Unsplash. Design: HTML5 UP.

Toggle