SlideShare a Scribd company logo
1 of 39
Principles of Computing
Sequences- (Tuples and Dictionaries)
Tuples
• Tuples are very similar to lists, but they are immutable (i.e.,
unchangeable)
• Tuples are written with round brackets as follows:
t1 = (1, 2, 3)
t2 = (“a”, “b”, “c”, ”d”)
t3 = (200, “A”, [4, 5], 3.2)
print(t1)
print(t2)
print(t3)
• A tuple is a sequence of values, which can be of any type and
they are indexed by integer. Tuples are just like list, but we can’t change
values of tuples in place. Thus tuples are immutable.
• The index value of tuple starts from 0.
• A tuple consists of a number of values separated by commas. For
example:
• >>> T= (10, 20, 30, 40)
• >>> print (T)
• (10, 20, 30, 40)
WHAT IS TUPLE?
CREATING EMPTY TUPLE
ACCESSING TUPLE
Tuples
• Like lists, tuples can:
• Contain any and different types of elements
• Contain duplicate elements (e.g., (1, 1, 2))
• Be indexed exactly in the same way (i.e., using the [] brackets)
• Be sliced exactly in the same way (i.e., using the [::] notation)
• Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”))
• Be repeated (e.g., t = (“a”, “b”) * 10)
• Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4))
• Be passed to a function, but will result in pass-by-value and not pass-by-
reference outcome since it is immutable
• Be iterated over
Examples
t1 = ("a", "b", "c")
print(t1[::-1])
t2 = ("a", "b", "c")
t3 = t1 + t2
print(t3)
t3 = t3 * 4
print(t3)
for i in t3:
print(i, end = " ")
print()
This will print the elements of t1 in
a reversed order, but will not change
t1 itself since it is immutable
This will concatenate t1 and t2 and
assign the result to t3 (again, t1 and
t2 will be unchanged since they are
immutable)
This will repeat t3 four times and
assign the result to t3. Hence,
t3 will be overwritten (i.e., NOT
changed in place- because it is
immutable-, but redefined with a
new value)
ACCESSING TUPLE USING LOOPS
ACCESSING TUPLE USING LOOPS
OUTPUT
CHECK IF ITEM EXISTS
OUTPUT
TUPLE LENGTH
OUTPUT
REMOVING A TUPLE
You cannot remove or delete or update items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
NOTE: TUPLES ARE IMMUTABLE
Examples
t4 = ((1, 2, 3), ("a", "b", "c"))
for j in t4:
for k in j:
print(k,end = " ")
print()
This is an example of nesting, where
a matrix with 2 rows and
3 columns is created. The first row
includes the elements 1, 2, and 3.
The second row includes the elements
“a”, “b”, and “c”.
This outer loop iterates over each
element in t4; that is, it gets first the
element (1, 2, 3) and second the
element (“a”, “b”, “c”)
This inner loop iterates over each
element read by the outer loop; that
is, it first iterates over the elements
of the element (1, 2, 3), and second
it iterates over the elements of the
element (“a”, “b”, “c”)
Examples
def func1(t):
t = t * 2
t = (1, 2, 3)
print(t)
func1(t)
print(t)
This will output (1, 2, 3)
This will also output (1, 2, 3) since
tuples are immutable, hence, will
always exhibit a passed-by-value
behavior
This change on t remains local to the function
since a value of t was passed and not a
reference to it
TUPLE METHODS
Python provides two built-in methods that you can use on tuples.
1. count() Method
2. index() Method
Using Functions with Tuples
• You can also use functions with tuples
t1 = (1, 2, 3, 1, 5, 1)
print(t1.count(1))
print(t1.index(1))
The count(x) function returns the number of
elements with the specified value x (e.g., x is 1
in this example)
The index(x) function returns the index of the
first element with the specified value x (e.g., x
is 1 in this example)
Output:
3
0
In fact, Python has only these two built-in functions that can be used
on tuples
TUPLE METHODS
1. count() Method
Return the number of times the value appears in the tuple
Count() method
returns total no
times ‘banana’
present in the
given tuple
TUPLE METHODS
2. index() Method
index() Method returns index of “banana” i.e
1
index()
Method
DIFFERENCE BETWEEN LIST AND TUPLE
LIST TUPLE
Syntax for list is slightly different
comparing with tuple
Syntax for tuple is slightly different
comparing with lists
Weekdays=[‘Sun’,’Mon’,
‘wed’,46,67]
type(Weekdays)
class<‘lists’>
twdays =(‘Sun’, ‘mon', ‘tue', 634)
type(twdays)
class<‘tuple’>
List uses [ and ] (square brackets)
to bind the elements.
Tuple uses rounded brackets( and ) to
bind the elements.
1. Write a Python program to create a tuple.
#Create an empty tuple
x = ()
print(x)
#Create an empty tuple with tuple() function
#built-in Python
tuplex = tuple()
print(tuplex)
TUPLE - BELLOW AVERAGE PROGRAMS
2. Write a Python program to create a tuple with
different data types
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
TUPLE - BELLOW AVERAGE PROGRAMS
3. Write a Python program to unpack a tuple in several variables
#create a tuple
tuplex = 4, 8, 3
print(tuplex)
n1, n2, n3 = tuplex
#unpack a tuple in variables
print(n1 + n2 + n3)
#the number of variables must be equal to the number of items
of the tuple
n1, n2, n3, n4= tuplex
TUPLE - BELLOW AVERAGE PROGRAMS
4 Write a Python program to find the index of an item of a tuple.
#create a tuple
tuplex = tuple("index tuple")
print(tuplex)
#get index of the first item whose value is passed as parameter
index = tuplex.index("p")
print(index)
#define the index from which you want to search
index = tuplex.index("p", 5)
TUPLE - AVERAGE PROGRAMS
print(index)
#define the segment of the tuple to be searched
index = tuplex.index("e", 3, 6)
print(index)
#if item not exists in the tuple return ValueError Exception
index = tuplex.index("y")
TUPLE - AVERAGE PROGRAMS
5. Write a Python program to add an item in a tuple.
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an
element and it will create a new tuple
tuplex = tuplex + (9,)
print(tuplex)
TUPLE - AVERAGE PROGRAMS
5. Write a Python program to add an item in a tuple.
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
TUPLE - AVERAGE PROGRAMS
Towards Dictionaries
• Lists and tuples hold elements with only integer indices
• So in essence, each element has an index (or a key) which can only be
an integer, and a value which can be of any type (e.g., in the above
list/tuple, the first element has key 0 and value 45)
• What if we want to store elements with non-integer indices (or keys)?
45 “Coding” 4.5 7 89
0 1 2 3 4
Integer
Indices
Dictionaries
• In Python, you can use a dictionary to store elements with keys of any
types (not necessarily only integers like lists and tuples) and values of
any types as well
• The above dictionary can be defined in Python as follows:
dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, “abc":89}
45 “Coding” 4.5 7 89
“NUM” 1000 2000 3.4 “abc”
keys of different types
Each element is a key:value pair, and elements are separated by commas
key value
Values of different types
Dictionaries
• In summary, dictionaries:
• Can contain any and different types of elements (i.e., keys and values)
• Can contain only unique keys but duplicate values
• Can be indexed but only through keys (i.e., dic2[“a”] will return 2 but dic2[0]
will return an error since there is no element with key 0 in dic2 above)
Output: {'a': 2, 'b': 2}
dic2 = {"a":1, "a":2, "b":2}
print(dic2)
The element “a”:2 will override the element “a”:1
because only ONE element can have key “a”
Dictionaries
• In summary, dictionaries:
• CANNOT be concatenated
• CANNOT be repeated
• Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}}
• Can be passed to a function and will result in a pass-by-reference and not
pass-by-value behavior since it is immutable (like lists)
Output:
{'first': {1: 1}, 'second': {2: 'a'}}
{'first': [1, 2, 3], 'second': {2: 'a'}}
def func1(d):
d["first"] = [1, 2, 3]
dic = {"first":{1:1},
"second":{2:"a"}}
print(dic)
func1(dic)
print(dic)
Dictionaries
• In summary, dictionaries:
• Can be iterated over
Output:
dic = {"first": 1, "second": 2, "third": 3}
for i in dic:
print(i)
How to get the values?
first
second
third
ONLY the keys will be returned.
Dictionaries
• In summary, dictionaries:
• Can be iterated over
Output:
dic = {"first": 1, "second": 2, "third": 3}
for i in dic:
print(dic[i])
1
2
3
Values can be accessed via indexing!
Adding Elements to a Dictionary
• How to add elements to a dictionary?
• By indexing the dictionary via a key and assigning a corresponding value
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
Adding Elements to a Dictionary
• How to add elements to a dictionary?
• By indexing the dictionary via a key and assigning a corresponding value
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic[”second"] = 4
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second’: 4, 'third': 3}
If the key already exists,
the value will be overridden
Deleting Elements to a Dictionary
• How to delete elements in a dictionary?
• By using del
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
del dic["first"]
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
{'second': 2, 'third': 3, 'fourth': 4}
Deleting Elements to a Dictionary
• How to delete elements in a dictionary?
• Or by using the function pop(key)
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
dic.pop(“first”)
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
{'second': 2, 'third': 3, 'fourth': 4}
Dictionary Functions
• Many other functions can also be used with dictionaries
Function Description
dic.clear() Removes all the elements from dictionary dic
dic.copy() Returns a copy of dictionary dic
dic.items() Returns a list containing a tuple for each key-value pair in
dictionary dic
dic.get(k) Returns the value of the specified key k from dictionary dic
dic.keys() Returns a list containing all the keys of dictionary dic
dic.pop(k) Removes the element with the specified key k from dictionary dic
Dictionary Functions
• Many other functions can also be used with dictionaries
Function Description
dic.popitem() Removes the last inserted key-value pair in dictionary dic
dic.values() Returns a list of all the values in dictionary dic
DIFFERENCE BETWEEN LIST AND TUPLE
LIST TUPLE
List can be edited once it is
created in python. Lists are
mutable data structure.
A tuple is a list which one cannot edit
once it is created in Python code. The
tuple is an immutable data structure
More methods or functions are
associated with lists.
Compare to lists tuples have Less
methods or functions.

More Related Content

Similar to Tuples-and-Dictionaries.pptx

02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptxssuser88c564
 
1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptxVGaneshKarthikeyan
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdfT PRIYA
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdfTuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdfTHIRUGAMING1
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua tableShuai Yuan
 
computer science tuple in python project.pdf
computer science tuple in python project.pdfcomputer science tuple in python project.pdf
computer science tuple in python project.pdfREXGAMING6
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology InitiativeBasil Bibi
 

Similar to Tuples-and-Dictionaries.pptx (20)

02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptx
 
1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
tupple.pptx
tupple.pptxtupple.pptx
tupple.pptx
 
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdfTuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
 
Python standard data types
Python standard data typesPython standard data types
Python standard data types
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua table
 
computer science tuple in python project.pdf
computer science tuple in python project.pdfcomputer science tuple in python project.pdf
computer science tuple in python project.pdf
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Lecture 09.pptx
Lecture 09.pptxLecture 09.pptx
Lecture 09.pptx
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Python data type
Python data typePython data type
Python data type
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 

Recently uploaded

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Tuples-and-Dictionaries.pptx

  • 1. Principles of Computing Sequences- (Tuples and Dictionaries)
  • 2. Tuples • Tuples are very similar to lists, but they are immutable (i.e., unchangeable) • Tuples are written with round brackets as follows: t1 = (1, 2, 3) t2 = (“a”, “b”, “c”, ”d”) t3 = (200, “A”, [4, 5], 3.2) print(t1) print(t2) print(t3)
  • 3. • A tuple is a sequence of values, which can be of any type and they are indexed by integer. Tuples are just like list, but we can’t change values of tuples in place. Thus tuples are immutable. • The index value of tuple starts from 0. • A tuple consists of a number of values separated by commas. For example: • >>> T= (10, 20, 30, 40) • >>> print (T) • (10, 20, 30, 40) WHAT IS TUPLE?
  • 6. Tuples • Like lists, tuples can: • Contain any and different types of elements • Contain duplicate elements (e.g., (1, 1, 2)) • Be indexed exactly in the same way (i.e., using the [] brackets) • Be sliced exactly in the same way (i.e., using the [::] notation) • Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”)) • Be repeated (e.g., t = (“a”, “b”) * 10) • Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4)) • Be passed to a function, but will result in pass-by-value and not pass-by- reference outcome since it is immutable • Be iterated over
  • 7. Examples t1 = ("a", "b", "c") print(t1[::-1]) t2 = ("a", "b", "c") t3 = t1 + t2 print(t3) t3 = t3 * 4 print(t3) for i in t3: print(i, end = " ") print() This will print the elements of t1 in a reversed order, but will not change t1 itself since it is immutable This will concatenate t1 and t2 and assign the result to t3 (again, t1 and t2 will be unchanged since they are immutable) This will repeat t3 four times and assign the result to t3. Hence, t3 will be overwritten (i.e., NOT changed in place- because it is immutable-, but redefined with a new value)
  • 9. ACCESSING TUPLE USING LOOPS OUTPUT
  • 10. CHECK IF ITEM EXISTS OUTPUT
  • 12. REMOVING A TUPLE You cannot remove or delete or update items in a tuple. Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely: NOTE: TUPLES ARE IMMUTABLE
  • 13. Examples t4 = ((1, 2, 3), ("a", "b", "c")) for j in t4: for k in j: print(k,end = " ") print() This is an example of nesting, where a matrix with 2 rows and 3 columns is created. The first row includes the elements 1, 2, and 3. The second row includes the elements “a”, “b”, and “c”. This outer loop iterates over each element in t4; that is, it gets first the element (1, 2, 3) and second the element (“a”, “b”, “c”) This inner loop iterates over each element read by the outer loop; that is, it first iterates over the elements of the element (1, 2, 3), and second it iterates over the elements of the element (“a”, “b”, “c”)
  • 14. Examples def func1(t): t = t * 2 t = (1, 2, 3) print(t) func1(t) print(t) This will output (1, 2, 3) This will also output (1, 2, 3) since tuples are immutable, hence, will always exhibit a passed-by-value behavior This change on t remains local to the function since a value of t was passed and not a reference to it
  • 15. TUPLE METHODS Python provides two built-in methods that you can use on tuples. 1. count() Method 2. index() Method
  • 16. Using Functions with Tuples • You can also use functions with tuples t1 = (1, 2, 3, 1, 5, 1) print(t1.count(1)) print(t1.index(1)) The count(x) function returns the number of elements with the specified value x (e.g., x is 1 in this example) The index(x) function returns the index of the first element with the specified value x (e.g., x is 1 in this example) Output: 3 0 In fact, Python has only these two built-in functions that can be used on tuples
  • 17. TUPLE METHODS 1. count() Method Return the number of times the value appears in the tuple Count() method returns total no times ‘banana’ present in the given tuple
  • 18. TUPLE METHODS 2. index() Method index() Method returns index of “banana” i.e 1 index() Method
  • 19. DIFFERENCE BETWEEN LIST AND TUPLE LIST TUPLE Syntax for list is slightly different comparing with tuple Syntax for tuple is slightly different comparing with lists Weekdays=[‘Sun’,’Mon’, ‘wed’,46,67] type(Weekdays) class<‘lists’> twdays =(‘Sun’, ‘mon', ‘tue', 634) type(twdays) class<‘tuple’> List uses [ and ] (square brackets) to bind the elements. Tuple uses rounded brackets( and ) to bind the elements.
  • 20. 1. Write a Python program to create a tuple. #Create an empty tuple x = () print(x) #Create an empty tuple with tuple() function #built-in Python tuplex = tuple() print(tuplex) TUPLE - BELLOW AVERAGE PROGRAMS
  • 21. 2. Write a Python program to create a tuple with different data types #Create a tuple with different data types tuplex = ("tuple", False, 3.2, 1) print(tuplex) TUPLE - BELLOW AVERAGE PROGRAMS
  • 22. 3. Write a Python program to unpack a tuple in several variables #create a tuple tuplex = 4, 8, 3 print(tuplex) n1, n2, n3 = tuplex #unpack a tuple in variables print(n1 + n2 + n3) #the number of variables must be equal to the number of items of the tuple n1, n2, n3, n4= tuplex TUPLE - BELLOW AVERAGE PROGRAMS
  • 23. 4 Write a Python program to find the index of an item of a tuple. #create a tuple tuplex = tuple("index tuple") print(tuplex) #get index of the first item whose value is passed as parameter index = tuplex.index("p") print(index) #define the index from which you want to search index = tuplex.index("p", 5) TUPLE - AVERAGE PROGRAMS
  • 24. print(index) #define the segment of the tuple to be searched index = tuplex.index("e", 3, 6) print(index) #if item not exists in the tuple return ValueError Exception index = tuplex.index("y") TUPLE - AVERAGE PROGRAMS
  • 25. 5. Write a Python program to add an item in a tuple. #create a tuple tuplex = (4, 6, 2, 8, 3, 1) print(tuplex) #tuples are immutable, so you can not add new elements #using merge of tuples with the + operator you can add an element and it will create a new tuple tuplex = tuplex + (9,) print(tuplex) TUPLE - AVERAGE PROGRAMS
  • 26. 5. Write a Python program to add an item in a tuple. #adding items in a specific index tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5] print(tuplex) #converting the tuple to list listx = list(tuplex) #use different ways to add items in list listx.append(30) tuplex = tuple(listx) print(tuplex) TUPLE - AVERAGE PROGRAMS
  • 27. Towards Dictionaries • Lists and tuples hold elements with only integer indices • So in essence, each element has an index (or a key) which can only be an integer, and a value which can be of any type (e.g., in the above list/tuple, the first element has key 0 and value 45) • What if we want to store elements with non-integer indices (or keys)? 45 “Coding” 4.5 7 89 0 1 2 3 4 Integer Indices
  • 28. Dictionaries • In Python, you can use a dictionary to store elements with keys of any types (not necessarily only integers like lists and tuples) and values of any types as well • The above dictionary can be defined in Python as follows: dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, “abc":89} 45 “Coding” 4.5 7 89 “NUM” 1000 2000 3.4 “abc” keys of different types Each element is a key:value pair, and elements are separated by commas key value Values of different types
  • 29. Dictionaries • In summary, dictionaries: • Can contain any and different types of elements (i.e., keys and values) • Can contain only unique keys but duplicate values • Can be indexed but only through keys (i.e., dic2[“a”] will return 2 but dic2[0] will return an error since there is no element with key 0 in dic2 above) Output: {'a': 2, 'b': 2} dic2 = {"a":1, "a":2, "b":2} print(dic2) The element “a”:2 will override the element “a”:1 because only ONE element can have key “a”
  • 30. Dictionaries • In summary, dictionaries: • CANNOT be concatenated • CANNOT be repeated • Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}} • Can be passed to a function and will result in a pass-by-reference and not pass-by-value behavior since it is immutable (like lists) Output: {'first': {1: 1}, 'second': {2: 'a'}} {'first': [1, 2, 3], 'second': {2: 'a'}} def func1(d): d["first"] = [1, 2, 3] dic = {"first":{1:1}, "second":{2:"a"}} print(dic) func1(dic) print(dic)
  • 31. Dictionaries • In summary, dictionaries: • Can be iterated over Output: dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(i) How to get the values? first second third ONLY the keys will be returned.
  • 32. Dictionaries • In summary, dictionaries: • Can be iterated over Output: dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(dic[i]) 1 2 3 Values can be accessed via indexing!
  • 33. Adding Elements to a Dictionary • How to add elements to a dictionary? • By indexing the dictionary via a key and assigning a corresponding value Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
  • 34. Adding Elements to a Dictionary • How to add elements to a dictionary? • By indexing the dictionary via a key and assigning a corresponding value Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic[”second"] = 4 print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second’: 4, 'third': 3} If the key already exists, the value will be overridden
  • 35. Deleting Elements to a Dictionary • How to delete elements in a dictionary? • By using del Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) del dic["first"] print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}
  • 36. Deleting Elements to a Dictionary • How to delete elements in a dictionary? • Or by using the function pop(key) Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) dic.pop(“first”) print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}
  • 37. Dictionary Functions • Many other functions can also be used with dictionaries Function Description dic.clear() Removes all the elements from dictionary dic dic.copy() Returns a copy of dictionary dic dic.items() Returns a list containing a tuple for each key-value pair in dictionary dic dic.get(k) Returns the value of the specified key k from dictionary dic dic.keys() Returns a list containing all the keys of dictionary dic dic.pop(k) Removes the element with the specified key k from dictionary dic
  • 38. Dictionary Functions • Many other functions can also be used with dictionaries Function Description dic.popitem() Removes the last inserted key-value pair in dictionary dic dic.values() Returns a list of all the values in dictionary dic
  • 39. DIFFERENCE BETWEEN LIST AND TUPLE LIST TUPLE List can be edited once it is created in python. Lists are mutable data structure. A tuple is a list which one cannot edit once it is created in Python code. The tuple is an immutable data structure More methods or functions are associated with lists. Compare to lists tuples have Less methods or functions.