SlideShare a Scribd company logo
UNIT-4
COMPOUND DATA
LISTS,TUPLES,DICTIONARIES
LIST DEFINITION
• A list is an ordered set of values, where each
value is identified by an index.
• The values that make up a list are called its
elements.
• Lists and strings and other things that behave
like ordered sets are called sequences.
• Updating in the existing list is possible.
EXAMPLES
• LIST1=[“maths”,”physics”,”chemistry”]
• LIST2=[1,2,3,4,5]
• WORDS=[“ameliorate”, “castigate”]
• numbers=[17, 123]
ACCESSING ELEMENTS IN LIST
>>>LIST2=[1,2,3,4,5]
>>> print(LIST2[0])
1
>>>print(LIST2[-1])
5
>>>WORDS=[“hello”, “hai”]
>>>print (WORDS[1])
hai
UPDATING IN A LIST
• In list you can add the element using the
method append()
• list.append(obj)
Example
>>> list2=[1,2,3,4,5]
>>>list2.append(9)
>>>print (list2[])
[1,2,3,4,5,9]
Delete list elements
• To remove a element in a list, you can use either del statement
if you exactly know which elements you are deleting or
remove() method if you don’t know.
• Example
>>>numbers=[17, 123,54,78,99,45,67]
>>>del list[2]
>>>print(numbers[])
[17, 123,78,99,45,67]
>>>numbers.remove(123)
>>>print(numbers[])
[17,78,99,45,67]
List operations
• Lists respond to the + and * operators much
like strings; they mean concatenation and
repetition here too, except that the result is a
new list, not a string.
BASIC LIST OPERATIONS
PYTHON EXXPRESSION RESULTS DESCRIPTION
Len([1,2,3]) 3 length
[1,2,3]+[4,5] [1,2,3,4,5] concatenation
[‘hi’]*2 [‘hi’ ‘hi’] repetition
2 in [1,2,3],
5 not in [1,2,4]
True
True Membership
for x in [1,2,3,4,5] 1 2 3 4 5 iteration
List slices
• A subsequence of a sequence is called a slice
and the operation that extracts a subsequence
is called slicing.
• Like with indexing, we use square brackets ([ ])
as the slice operator, but instead of one
integer value inside we have two, separated
by a colon (:)
Example
List methods
• list.append()
• list.insert()
• list.extend()
• list.remove()
• list.pop()
• list.index()
• list.copy()
• list.copy()
• list.reverse()
• list.count()
• list.sort()
• list.clear()
List .append()
• append(x) method is used to add an item to
the end of a list.
• Example
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>Veggies.append(potato)
>>>Print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’beans’,’potato’]
List.insert()
• The list.insert(i,x) method takes two arguments,
with i being the index position you would like to
add an item to, and x being the item itself.
• Example
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>veggies.insert(3,’brinjal’)
>>>print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’brinjal’,’beans’]
List.extend()
• The list.extend(L) method, which takes in a
second list as its argument.
• Example
• >>>fruits=[‘apple’,’orange’,’grapes’]
• >>>veggies.extend(fruits)
• >>>print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’beans’,‘apple’,
’orange’,’grapes’]
List.remove()
• To remove an item from a list
• remove(x) method which removes the first item
in a list whose value is equivalent to x
• Example
• >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
• >>>veggies.remove(‘cabbage’)
• >>>print(veggies[])
[‘carrot’,’beetroot’,’beans’]
List.pop()
• The list.pop([i]) method to return the item
at the given index position from the list
and then remove that item.
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>print(veggies.pop(2))
>>>print(veggies[])
[‘carrot’,’cabbage’,’beans’]
list.index()
• lists start to get long, it becomes more difficult
for us to count out our items to determine at
what index position a certain value is located.
• >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>> print(veggies.index(‘beans’))
3
list.copy()
• If working with a list and may want to
manipulate it in multiple ways while still
having the original list available to us
unchanged, we can use list.copy() to make a
copy of the list.
• >>>items=veggies.copy()
• >>>print(items[])
[‘carrot’,’cabbage’,’beetroot’,’beans’]
list.reverse()
• Reverse the order of items in a list by using
the list.reverse() method.
>>>veggies.reverse()
>>>print(veggies[])
[‘beans’,’beetroot’,’cabbage’,’carrot’]
list.count()
• The list.count(x) method will return the
number of times the value x occurs within a
specified list.
>>>print(veggies.count())
4
List.sort()
• The list.sort() method to sort the items in a
list.
>>>list=[5,6,3,9,1]
>>>list.sort()
>>>print(list[])
[1,3,5,6,9]
List.clear()
• To remove all values contained in it by using
the list.clear() method.
>>>veggies.clear()
>>>print(veggies[])
[]
List range
>>>range(1,5)
[1, 2, 3, 4]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
List Loop
• A loop is a block of code that repeats itself
until it runs out of items to work with, or until
a certain condition is met.
• Tour=[‘chennai’,’mumbai’,’banglore’,’australia’]
for t in tour
print(t)
Example
• Tour=[‘chennai’,’mumbai’,’banglore’,’australia’]
for t in tour
print(t)
output:
chennai
mumbai
banglore
australia
Lists are mutable
• lists are mutable, which means we can change
their elements.
Example
List Deletion
UNIT-4.pptx python for engineering students
ALIASING
• if we assign one variable to another, both
variables refer to the same object.
>>>a=[13,14,6,8,9]
>>>b=a
>>>a is b
true
CLONING LISTS
• If we want to modify a list and also keep a
copy of the original, we need to be able to
make a copy of the list itself, not just the
reference.
• This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
UNIT-4.pptx python for engineering students
List parameters
• Passing a list as an argument actually passes a
reference to the list, not a copy of the list.
Example: def double (a_list):
Tuples
• A tuple is a sequence of immutable Python objects.
• Tuples are sequences, just like lists.
• Examples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d“)
Accessing Values in Tuples
• To access values in tuple, use the square brackets for slicing
along with the index or indices to obtain value available at that
index.
• Example
>>>tup1 = ('physics', 'chemistry', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>>print ("tup1[0]: ", tup1[0] ) #for positive indexing
>>>print ("tup2[1:5]: ", tup2[1:5]) # for slicing
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
• Tuples are immutable which means you
cannot update or change the values of tuple
elements.
• But it can be able to take portions of existing
tuples to create new tuples as the following
example demonstrates
>>>tup1 = (12, 34.56);
>>>tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
tup1[0] = 100;
# So let's create a new tuple as follows
>>>tup3 = tup1 + tup2;
>>>print (tup3)
Output:
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements
• Removing individual tuple elements is not possible.
Example:
tup = ('physics', 'chemistry', 1997, 2000)
print (tup)
del (tup )
print ("After deleting tup : " print tup)
Output:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last): File "test.py", line 9, in <module>
print (tup);
NameError: name 'tup' is not defined
Python Tuple Methods
Python Tuple Method
• count(x) -Return the number of items that is
equal to x
• index(x) -Return index of first item that is
equal to x
• my_tuple = ('a','p','p','l','e',)
# Count
print(my_tuple.count('p'))
# Output: 2
# Index
print(my_tuple.index('l'))
# Output: 3
Built-in Tuple Functions
cmp(tuple1, tuple2)-Compares elements of both tuples.
len(tuple)-Gives the total length of the tuple.
max(tuple)-Returns item from the tuple with max value.
min(tuple)-Returns item from the tuple with min value.
tuple(seq)-Converts a list into tuple
Tuple Membership Test
my_tuple = ('a','p','p','l','e',)
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
print('g' not in my_tuple)
Comparing tuples
• The comparison operators work with tuples
and other sequences.
• Python starts by comparing the first element
from each sequence.
Decorate
• A sequence by building a list of tuples with
one or more sort keys preceding the elements
from the sequence
Undecorate
• By extracting the sorted elements of the
sequence.
TUPLES AS RETURN VALUES
• a function can only return one value, but
if the value is a tuple, the effect is the same as
returning multiple values.
Example
DICTIONARIES
Definition for dictionaries
• Python dictionary is an unordered collection
of items.
• While other compound data types have only
value as an element, a dictionary has a key:
value pair.
• Dictionaries are enclosed by curly braces ({ })
and values can be assigned and accessed using
square braces ([]).
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
Access elements from a dictionary
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
change or add elements in a dictionary
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name':
'Jack'}
print(my_dict)
delete or remove elements from a dictionary
• Either remove individual dictionary elements
or clear the entire contents of a dictionary.
• You can also delete entire dictionary in a single
operation.
• To explicitly remove an entire dictionary, just
use the del statement.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'];
# remove entry with key 'Name'
dict.clear();
# remove all entries in dict
del dict ;
# delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Methods in dictionaries
UNIT-4.pptx python for engineering students
Advanced List Processing-list Comprehension
Illustrative programs
Revised with lab programs
Merge sort
Insertion sort
Selection sort
Quick sort
THANK YOU

More Related Content

PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPTX
datastrubsbwbwbbwcturesinpython-3-4.pptx
PPTX
Python list tuple dictionary .pptx
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
PDF
Python Variable Types, List, Tuple, Dictionary
PPTX
Brief Explanation On List and Dictionaries of Python
PPTX
Brixton Library Technology Initiative
PPT
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
datastrubsbwbwbbwcturesinpython-3-4.pptx
Python list tuple dictionary .pptx
ESIT135 Problem Solving Using Python Notes of Unit-3
Python Variable Types, List, Tuple, Dictionary
Brief Explanation On List and Dictionaries of Python
Brixton Library Technology Initiative
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON

Similar to UNIT-4.pptx python for engineering students (20)

PPTX
Pythonlearn-08-Lists.pptx
PPTX
UNIT-3 python and data structure alo.pptx
PPTX
Python Lecture 8
PPTX
DATA, EXPRESSIONS, STATEMENTS IN PYTHON PROGRAMMING
PPTX
Lists.pptx
PPTX
DictionariesPython Programming.One of the datatypes of Python which explains ...
PDF
python_avw - Unit-03.pdf
PPTX
Module-3.pptx
PPTX
An Introduction to Tuple List Dictionary in Python
PDF
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
PDF
Python elements list you can study .pdf
PPT
Programming in Python Lists and its methods .ppt
PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
DOC
Revision Tour 1 and 2 complete.doc
PDF
The Ring programming language version 1.10 book - Part 30 of 212
PDF
The Ring programming language version 1.8 book - Part 27 of 202
PPTX
Programming with Python_Unit-3-Notes.pptx
PPT
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
Pythonlearn-08-Lists.pptx
UNIT-3 python and data structure alo.pptx
Python Lecture 8
DATA, EXPRESSIONS, STATEMENTS IN PYTHON PROGRAMMING
Lists.pptx
DictionariesPython Programming.One of the datatypes of Python which explains ...
python_avw - Unit-03.pdf
Module-3.pptx
An Introduction to Tuple List Dictionary in Python
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Python elements list you can study .pdf
Programming in Python Lists and its methods .ppt
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Revision Tour 1 and 2 complete.doc
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.8 book - Part 27 of 202
Programming with Python_Unit-3-Notes.pptx
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
Ad

More from SabarigiriVason (6)

DOCX
sdn subject question paper -Int2 Set 1.docx
DOCX
sdn subject question paper -Int2 Set 2.docx
PPTX
SDN NOTES (2).pptx for engineering students
PPTX
UNIT –5.pptxpython for engineering students
PPTX
UNIT – 3.pptx for first year engineering
PPTX
UNIT-1.pptx python for engineering first year students
sdn subject question paper -Int2 Set 1.docx
sdn subject question paper -Int2 Set 2.docx
SDN NOTES (2).pptx for engineering students
UNIT –5.pptxpython for engineering students
UNIT – 3.pptx for first year engineering
UNIT-1.pptx python for engineering first year students
Ad

Recently uploaded (20)

PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
UNIT 4 Total Quality Management .pptx
PPT
Mechanical Engineering MATERIALS Selection
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Digital Logic Computer Design lecture notes
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
additive manufacturing of ss316l using mig welding
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
DOCX
573137875-Attendance-Management-System-original
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Operating System & Kernel Study Guide-1 - converted.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
UNIT 4 Total Quality Management .pptx
Mechanical Engineering MATERIALS Selection
R24 SURVEYING LAB MANUAL for civil enggi
Digital Logic Computer Design lecture notes
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
CYBER-CRIMES AND SECURITY A guide to understanding
additive manufacturing of ss316l using mig welding
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
573137875-Attendance-Management-System-original
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Model Code of Practice - Construction Work - 21102022 .pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk

UNIT-4.pptx python for engineering students

  • 2. LIST DEFINITION • A list is an ordered set of values, where each value is identified by an index. • The values that make up a list are called its elements. • Lists and strings and other things that behave like ordered sets are called sequences. • Updating in the existing list is possible.
  • 3. EXAMPLES • LIST1=[“maths”,”physics”,”chemistry”] • LIST2=[1,2,3,4,5] • WORDS=[“ameliorate”, “castigate”] • numbers=[17, 123]
  • 4. ACCESSING ELEMENTS IN LIST >>>LIST2=[1,2,3,4,5] >>> print(LIST2[0]) 1 >>>print(LIST2[-1]) 5 >>>WORDS=[“hello”, “hai”] >>>print (WORDS[1]) hai
  • 5. UPDATING IN A LIST • In list you can add the element using the method append() • list.append(obj) Example >>> list2=[1,2,3,4,5] >>>list2.append(9) >>>print (list2[]) [1,2,3,4,5,9]
  • 6. Delete list elements • To remove a element in a list, you can use either del statement if you exactly know which elements you are deleting or remove() method if you don’t know. • Example >>>numbers=[17, 123,54,78,99,45,67] >>>del list[2] >>>print(numbers[]) [17, 123,78,99,45,67] >>>numbers.remove(123) >>>print(numbers[]) [17,78,99,45,67]
  • 7. List operations • Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
  • 8. BASIC LIST OPERATIONS PYTHON EXXPRESSION RESULTS DESCRIPTION Len([1,2,3]) 3 length [1,2,3]+[4,5] [1,2,3,4,5] concatenation [‘hi’]*2 [‘hi’ ‘hi’] repetition 2 in [1,2,3], 5 not in [1,2,4] True True Membership for x in [1,2,3,4,5] 1 2 3 4 5 iteration
  • 9. List slices • A subsequence of a sequence is called a slice and the operation that extracts a subsequence is called slicing. • Like with indexing, we use square brackets ([ ]) as the slice operator, but instead of one integer value inside we have two, separated by a colon (:)
  • 11. List methods • list.append() • list.insert() • list.extend() • list.remove() • list.pop() • list.index() • list.copy() • list.copy() • list.reverse() • list.count() • list.sort() • list.clear()
  • 12. List .append() • append(x) method is used to add an item to the end of a list. • Example >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’] >>>Veggies.append(potato) >>>Print(veggies[]) [‘carrot’,’cabbage’,’beetroot’,’beans’,’potato’]
  • 13. List.insert() • The list.insert(i,x) method takes two arguments, with i being the index position you would like to add an item to, and x being the item itself. • Example >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’] >>>veggies.insert(3,’brinjal’) >>>print(veggies[]) [‘carrot’,’cabbage’,’beetroot’,’brinjal’,’beans’]
  • 14. List.extend() • The list.extend(L) method, which takes in a second list as its argument. • Example • >>>fruits=[‘apple’,’orange’,’grapes’] • >>>veggies.extend(fruits) • >>>print(veggies[]) [‘carrot’,’cabbage’,’beetroot’,’beans’,‘apple’, ’orange’,’grapes’]
  • 15. List.remove() • To remove an item from a list • remove(x) method which removes the first item in a list whose value is equivalent to x • Example • >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’] • >>>veggies.remove(‘cabbage’) • >>>print(veggies[]) [‘carrot’,’beetroot’,’beans’]
  • 16. List.pop() • The list.pop([i]) method to return the item at the given index position from the list and then remove that item. >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’] >>>print(veggies.pop(2)) >>>print(veggies[]) [‘carrot’,’cabbage’,’beans’]
  • 17. list.index() • lists start to get long, it becomes more difficult for us to count out our items to determine at what index position a certain value is located. • >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’] >>> print(veggies.index(‘beans’)) 3
  • 18. list.copy() • If working with a list and may want to manipulate it in multiple ways while still having the original list available to us unchanged, we can use list.copy() to make a copy of the list. • >>>items=veggies.copy() • >>>print(items[]) [‘carrot’,’cabbage’,’beetroot’,’beans’]
  • 19. list.reverse() • Reverse the order of items in a list by using the list.reverse() method. >>>veggies.reverse() >>>print(veggies[]) [‘beans’,’beetroot’,’cabbage’,’carrot’]
  • 20. list.count() • The list.count(x) method will return the number of times the value x occurs within a specified list. >>>print(veggies.count()) 4
  • 21. List.sort() • The list.sort() method to sort the items in a list. >>>list=[5,6,3,9,1] >>>list.sort() >>>print(list[]) [1,3,5,6,9]
  • 22. List.clear() • To remove all values contained in it by using the list.clear() method. >>>veggies.clear() >>>print(veggies[]) []
  • 23. List range >>>range(1,5) [1, 2, 3, 4] >>> range(1,10,2) [1, 3, 5, 7, 9]
  • 24. List Loop • A loop is a block of code that repeats itself until it runs out of items to work with, or until a certain condition is met. • Tour=[‘chennai’,’mumbai’,’banglore’,’australia’] for t in tour print(t)
  • 25. Example • Tour=[‘chennai’,’mumbai’,’banglore’,’australia’] for t in tour print(t) output: chennai mumbai banglore australia
  • 26. Lists are mutable • lists are mutable, which means we can change their elements.
  • 30. ALIASING • if we assign one variable to another, both variables refer to the same object. >>>a=[13,14,6,8,9] >>>b=a >>>a is b true
  • 31. CLONING LISTS • If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference. • This process is sometimes called cloning, to avoid the ambiguity of the word copy.
  • 33. List parameters • Passing a list as an argument actually passes a reference to the list, not a copy of the list. Example: def double (a_list):
  • 34. Tuples • A tuple is a sequence of immutable Python objects. • Tuples are sequences, just like lists. • Examples tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = ("a", "b", "c", "d“)
  • 35. Accessing Values in Tuples • To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. • Example >>>tup1 = ('physics', 'chemistry', 1997, 2000) >>> tup2 = (1, 2, 3, 4, 5, 6, 7 ) >>>print ("tup1[0]: ", tup1[0] ) #for positive indexing >>>print ("tup2[1:5]: ", tup2[1:5]) # for slicing Output: tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]
  • 36. Updating Tuples • Tuples are immutable which means you cannot update or change the values of tuple elements. • But it can be able to take portions of existing tuples to create new tuples as the following example demonstrates
  • 37. >>>tup1 = (12, 34.56); >>>tup2 = ('abc', 'xyz'); # Following action is not valid for tuples tup1[0] = 100; # So let's create a new tuple as follows >>>tup3 = tup1 + tup2; >>>print (tup3) Output: (12, 34.56, 'abc', 'xyz')
  • 38. Delete Tuple Elements • Removing individual tuple elements is not possible. Example: tup = ('physics', 'chemistry', 1997, 2000) print (tup) del (tup ) print ("After deleting tup : " print tup) Output: ('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print (tup); NameError: name 'tup' is not defined
  • 39. Python Tuple Methods Python Tuple Method • count(x) -Return the number of items that is equal to x • index(x) -Return index of first item that is equal to x
  • 40. • my_tuple = ('a','p','p','l','e',) # Count print(my_tuple.count('p')) # Output: 2 # Index print(my_tuple.index('l')) # Output: 3
  • 41. Built-in Tuple Functions cmp(tuple1, tuple2)-Compares elements of both tuples. len(tuple)-Gives the total length of the tuple. max(tuple)-Returns item from the tuple with max value. min(tuple)-Returns item from the tuple with min value. tuple(seq)-Converts a list into tuple
  • 42. Tuple Membership Test my_tuple = ('a','p','p','l','e',) # In operation # Output: True print('a' in my_tuple) # Output: False print('b' in my_tuple) # Not in operation # Output: True print('g' not in my_tuple)
  • 43. Comparing tuples • The comparison operators work with tuples and other sequences. • Python starts by comparing the first element from each sequence.
  • 44. Decorate • A sequence by building a list of tuples with one or more sort keys preceding the elements from the sequence
  • 45. Undecorate • By extracting the sorted elements of the sequence.
  • 46. TUPLES AS RETURN VALUES • a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.
  • 49. Definition for dictionaries • Python dictionary is an unordered collection of items. • While other compound data types have only value as an element, a dictionary has a key: value pair. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
  • 50. # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')])
  • 51. Access elements from a dictionary my_dict = {'name':'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age'))
  • 52. change or add elements in a dictionary my_dict = {'name':'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict)
  • 53. delete or remove elements from a dictionary • Either remove individual dictionary elements or clear the entire contents of a dictionary. • You can also delete entire dictionary in a single operation. • To explicitly remove an entire dictionary, just use the del statement.
  • 54. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']
  • 58. Illustrative programs Revised with lab programs Merge sort Insertion sort Selection sort Quick sort