0% found this document useful (0 votes)
20 views157 pages

Unit-3_Collections and Sequences

Uploaded by

singhakhil52141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views157 pages

Unit-3_Collections and Sequences

Uploaded by

singhakhil52141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 157

Quality Content for Outcome based Learning

3.Python Collections and Sequences

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline
© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

2
Copyright © 2021, ABES Engineering College
Objective of Collections/Sequences

To describe the importance of list , string, tuple , dictionary and set in python

To uses to store multiple data values.

To use the index to update, add, and remove items

To use the data structures with out indexes

To explain the difference among different Collections

To select collections built-in functions in Python to write programs in Python.

3
Copyright © 2021, ABES Engineering College
Topics Covered

Day 1 Day 2 Day 3 Day 4

3.1 Introduction 3.2 String 3.3 List 3.3 List


• 3.2 String • Updation • Creation • Loops
• Creation of • Deletion • Accessing • Nested List
String • Built-in- • Update • List
• Accessing the methods • Built in Comprehensi
String • Operations methods ons
• String
Formatters
• Loops with
Strings

4
Copyright © 2021, ABES Engineering College
Topics Covered

Day 5 Day 6 Day 7 Day 8

3.4 Tuple 3. 5 Dictionary 3.5 Dictionary 3.6 Set


• Creation • Creation • Built in • Creation
• Accessing • Accessing Methods • Assessing
• Modification • Modification • Loops and • Modification
Conditions • Built in
• Built in
Methods methods
• Operations • Operators
• Loops
• Frozen set

5
Copyright © 2021, ABES Engineering College
Session Plan - Day 1

3 Introduction to Python Collections and Sequences


3.1 String
 Creation of String
 Assessing of String
 Updation of String
 Examples
 Review Questions

6
Copyright © 2021, ABES Engineering College
Introduction

In real life we need to store data like-


 Name of students – A sequence of alphabet character
 Marks of n students – A sequence of either integer or float value
 Student’s record – A sequence of name, branch, roll number, address etc
So to represent these type of data in python provides us some built in collections.

7
Copyright © 2021, ABES Engineering College
Contd…
Representation of Python Collections with the help of Figure:

 If data is the combination of


numeric data, alphanumeric or
of different types than we go
for List, Tuple or set .

 If data is in the form of key-


value pair than we go for
dictionary.

8
Copyright © 2021, ABES Engineering College
String
A string is a sequence of alphanumeric and
special character.

String is the collection of characters, it may


compose of alphanumeric and special
characters.

Strings are created in many ways using


single quotes or double-quotes.

Alphanumeric characters: a-z, A-Z, 0-9; Special symbol: *, -, +, $, @, whitespace …. etc

9
Copyright © 2021, ABES Engineering College
Creation of Empty String

Empty String

 An empty string is a string having no


character.
 We have three ways to create an empty
string as shown in syntax.
 An Empty String is created by single quotes,
double quotes and str().

10
Copyright © 2021, ABES Engineering College
Creation of Non Empty String

 A non-empty string is a sequence of alphanumeric character with at least one character.

 A non-empty string is created by using single quotes and double quotes

11
Copyright © 2021, ABES Engineering College
Assessing the String

 String Element can be accessed using Square


Bracket.

 These Square brackets [ ] take an index as


input.

 In Python we have two types of Indexing.

 Positive Indexing
 Negative Indexing

12
Copyright © 2021, ABES Engineering College
Positive Indexing

 Positive indexing
start from Zero (0)
and from left hand
side i.e. first
character store at
index 0, second at
index 1 and so on.

 Every character of
string has some
index value.

13
Copyright © 2021, ABES Engineering College
Negative Indexing

 Negative
Indexing starts
from negative
indexing start
from -1 and
from right-hand
side.

 Last character
store at index -
1 and as we
move towards
the left, it keeps
increasing like -
2, -3, and so
on.

14
Copyright © 2021, ABES Engineering College
Example

 Write a program to print character 'P' and 'L' using positive indexing and negative indexing.
Assume a string st = 'I Like Python’, is given.

15
Copyright © 2021, ABES Engineering College
String Slicing

 String slicing is the way of selection


of substring.

 String 'Like' is substring in given 'I Like


Python' string.

 [] we can access string characters by


giving indexes if we use colon inside
square bracket like [:] it becomes a
slicing operator in Python.

16
Copyright © 2021, ABES Engineering College
Syntax of String Slicing

 Start index: Index from


which slicing starts.

 End Index: Index up to


which slicing end.

 Step value is optional.

17
Copyright © 2021, ABES Engineering College
Examples of String Slicing

Example Explanation Syntax

st[ 2 : 6 ] It starts with the 2nd index and ending with (6It
starts with the 2nd index and ending with (6-1=5)th
index.-1=5)th index.
st[ 0 : 6 : 2 ] It starts with index 0th and end with (6-1=5) th. Step
is 2 So, it will give value at index 0,2,4

st[ 12 : 6 : -1] It starts slicing from 12th index up to 6-1=5th index.


12th to 6th in opposite direction because step is
negative.

18
Copyright © 2021, ABES Engineering College
Contd..

Example Explanation Syntax

st[ -11 : -7 ] It starts with -11th index and ending with (-


7-1 = -8)th index.

[:] The operator gives the complete original


string.*

[:6] Start index is missing and step is +1, So


it will start from 0 till 6-1=5th index.*

19
Copyright © 2021, ABES Engineering College
Contd..

Example Explanation Syntax

st[ 7 : ] It will start from index 7 to last index ( Last


index missing )*

st[ : : -1] Step is -1, So start index will be the last


index and end index will be first index
when start and end is missing.
st[ 2 : 6 : -1 ] This is explaining in Note Section **
Output – Empty string

20
Copyright © 2021, ABES Engineering College
Important Points to Remember

Note about *, **

 * When start index is missing it will start from either first character or from last. It
depends on step sign (positive or negative).
 * When end index is missing it will execute till last character or first character. It depends
on step sign (positive or negative).
 * When we take negative steps it will scan from start to end in opposite direction.
 ** In the case of step is positive or negative the slicing will be done as below given
algorithm.

21
Copyright © 2021, ABES Engineering College
Comparison

22
Copyright © 2021, ABES Engineering College
Updation in String
 Strings in python are Immutable(un-changeable) sequences, which means it does not support new
element assignment using indexes.

 Lets try to understand this concept with the help of an example

In the above example string does not allow assigning a new element, because item assignment does
not support by string.

23
Copyright © 2021, ABES Engineering College
Contd..
1. What will be the output of the following code snippets?

A. come to Myso

B. come to Mys

C. lcome to Mys\

D. lcome to Myso

24
Copyright © 2021, ABES Engineering College
Contd..
2. What will be the output of the following code Comparison?

A. True
False

B. False
False

25
Copyright © 2021, ABES Engineering College
Contd..
3. What will be the output of the following code snippet?

A. ES

B. En

C. ES En

D. ESEn

26
Copyright © 2021, ABES Engineering College
Contd..
4. What will be the output of the following code snippet?

A. hellohowa
B. hellohowaaaaa
C. hellohowaaaaaaa
D. Error

27
Copyright © 2021, ABES Engineering College
Session Plan - Day 2

3.1 String
 Built in Methods
 Basic Operations
 String Formatters
 Loops with Strings
 Review Questions
 Practice Exercises

28
Copyright © 2021, ABES Engineering College
Deletion

 In String, we can’t reassign the string characters but we can delete the complete string
using del command.

 Lets try to understand this concept with the hep of an example

In the above example , after deletion when we try to print the string st it gives NameError : st not
defined.

29
Copyright © 2021, ABES Engineering College
String Built in methods:

 String supports a variety of Built-In


methods for achieving different types
of functionalities.

 All built-in methods provide us to use


as plug and play, we do not have to
implement it.

 In python methods are called using


dot(.) operator

30
Copyright © 2021, ABES Engineering College
String Built in methods:

Method Name Explanation Code Snippet

capitalize() Return a string with first letter capital


e.g.
i like python  I Like Python

casefold() Return string in lowercase

count() Return the number of occurrence of


substring.
In the first example “i” occurred 3 times.
In the second example “like” occurred 2
times.

31
Copyright © 2021, ABES Engineering College
String Built in methods:

Method Name Explanation Code Snippet

endswith() Return True if the string ends with the


given substring otherwise return
False.
startswith() Returns True if the string starts with
the given substring otherwise return
False.

find() Return the lowest index in String


where substring sub is found.
In example – there are two “like”.
1st “like” is at index-2 and 2nd at
index-16. It return 2.

32
Copyright © 2021, ABES Engineering College
String Built in methods:

Method Name Explanation Code Snippet

lower() Convert and return a string into lower


case

upper() Convert and return a string into upper


case

swapcase() In swaps cases, the lower case


becomes the upper case and vice
versa

33
Copyright © 2021, ABES Engineering College
String Built in methods:

Method Name Explanation Code Snippet

title() Converts the first character of each


word to upper case.

replace() Returns a string after replacing old


substring with new substring.

split() Splits the string from given separator


and returns a list of substring.
Note –
By default, value of separator is a
whitespace

34
Copyright © 2021, ABES Engineering College
String Built in methods:
Method Name Explanation Code Snippet

join() Concatenate any number of strings.


The string whose method is called is
inserted in between each given string.
The result is returned as a new string
strip() Return a copy of the string with
leading and trailing whitespace
removed.
isalnum() Return true if the string is
alphanumeric (Combination of a-z, A-
Z, 0-9)
Note – It will return false only if string
contains special character.

35
Copyright © 2021, ABES Engineering College
String Built in methods:
Method Name Explanation Code Snippet

isalpha() Return true if the string contains only


alphabets(Combination of a-z, A-Z)

isdecimal() Returns True if all characters in the


string are decimals

islower() Returns True if all characters in the


string are lower case

36
Copyright © 2021, ABES Engineering College
String Built in methods:

Method Name Explanation Code Snippet


len() Return length(No of character) of a
given string. This is a generic
function.

37
Copyright © 2021, ABES Engineering College
Basic Operations in String:

 Strings in Python support basic operations like concatenation, replication


and membership

 Concatenation means joining/combining two string into one.


 Replication means repeating same string multiple times.
 Membership tells a given string is member of another string or not.

38
Copyright © 2021, ABES Engineering College
Operations in String:
Method Name Explanation Code Snippet

+ Concatenation

It will merge/join second string at the


end of first string and return.

* Multiply (Replicas)
It will repeat same string multiple
times and return.
Note – multiply string only with
integer number.

in Membership
It will check a given substring is
present in another string or not.
Note – gives bool value (True/False)

39
Copyright © 2021, ABES Engineering College
Operations in String:
Method Name Explanation Code Snippet

Not in It's reverse of Membership

40
Copyright © 2021, ABES Engineering College
String Formatters:

 String formatting is the process of infusing things in the string dynamically and presenting
the string.

Why to use String Formatter??

 For different types of requirement to print the string in a formatted manner.

 Here, format implies that in what look and feel we want our strings to get printed.

 Python string provides a number of options for formatting.

41
Copyright © 2021, ABES Engineering College
String Formatters:

 String formatting is the process of infusing things in the string dynamically and presenting
the string.

Why to use String Formatter??

 For different types of requirement to print the string in a formatted manner.

 Here, format implies that in what look and feel we want our strings to get printed.

 Python string provides a number of options for formatting.

42
Copyright © 2021, ABES Engineering College
String format Style:
Escape Explanation Example
Sequence
\newline Ignores newline

\\ Backslash

Write a backslash in string

\' If we need to use single quotes in our


string like
Good Morning! Mr. 'BOB'

43
Copyright © 2021, ABES Engineering College
String format Style

Escape Explanation Example


Sequence
\" If we need to use double quotes in
our string like
Good Morning! Mr. 'BOB'

\n Newline

44
Copyright © 2021, ABES Engineering College
String Format()

Method 1: It is a beneficial method for formatting strings; it uses {} as a placeholder.

 We have placed two curly braces and arguments that give the format method filled in
the same output.

45
Copyright © 2021, ABES Engineering College
String Format()

 If we want to change the order of , we can give an index of parameters of format


method starting with 0th index.

46
Copyright © 2021, ABES Engineering College
String Format()

 If we want to change the order of , we can give an index of parameters of format


method starting with 0th index.

47
Copyright © 2021, ABES Engineering College
String Format()

 We can also use keywords arguments in format method, as shown in the


following example, as shown in figure.

48
Copyright © 2021, ABES Engineering College
String Format()

 We can also use format specifier in format method like in language ‘C’. Format
specifier are used to do following.

 Represent value of amount = 12.68456 at two decimal place


 Represent value of integer in Binary, Octal or Hexadecimal etc.

Note: In the above example b is used for binary representation.

49i
Copyright © 2021, ABES Engineering College
Format Specifiers

Format Specifier Explanation Example

b Use for Binary

o Use for Octal

X or x Use for Hexadecimal

50
Copyright © 2021, ABES Engineering College
Format Specifiers

Format Specifiers Explanation Example

d Use for Decimal

f Use for Float


Note – Place .n before f, for
representing floating point
precision. n is decimal places.

51
Copyright © 2021, ABES Engineering College
Formatting using f-string

 Fstring is the way of formatting as format method does but in an easier way.

 We include ‘f’ or ‘F’ as a prefix of string.

52
Copyright © 2021, ABES Engineering College
Can you answer these questions?
1. What will be the output of the following code snippet?

A. Hello how are you


B. Hello how are
C. hello how are you
D. Hello how re you

53
Copyright © 2021, ABES Engineering College
Can you answer these questions?
2. What will be the output of the following code snippet?

A. True

B. False

C. Error

D. None

54
Copyright © 2021, ABES Engineering College
Loops with Strings:

 Strings are sequence of character and iterable objects, so we can directly apply for loop
through string.
Example-1 Example -2
Scan/Iterate each character of string through Scan/Iterate each character of string directly
index using for loop. using for loop

55
Copyright © 2021, ABES Engineering College
Loops with Strings:

Example 3 – Write a program to print number of alphabets and digits in a given string.

56
Copyright © 2021, ABES Engineering College
Loops with Strings:

Example 4
To add 'ing' at the end of a given string (length should be at least 3).

 If the given string already ends with 'ing' then add 'ly' instead.
 If the string length of the given string is less than 3, leave it unchanged.

Sample String : 'abc'


Expected Output : 'abcing’

Sample String : 'string'


Expected Output : 'stringly'
.

57
Copyright © 2021, ABES Engineering College
Session Plan - Day 3

3.2 List
 Creation
 Accessing
 Updation
 Review Questions
 Practice Exercises

58
Copyright © 2021, ABES Engineering College
List

.  Python List is the most commonly used sequence.

 Important points about list are as follows.


 List elements are enclosed in square brackets [] and are comma separated.

 List is the sequence of class type ‘list’.

 List can contain elements of different data types.

 List is a mutable(changeable) sequence, would be discussed in detail in 3.2.3

 List allows duplicate elements.


 List elements are ordered, it means it give specific order to the elements, if new element is
added, by default it comes at the end of the list.

59
Copyright © 2021, ABES Engineering College
List

Real World Scenario:


List Representation
 List is used when there is a
possibility of elements of different
data type.

 For example record of a particular


student, having name as string,
roll.no as integer, marks as float,
father’s name as string.

 To contain this record list is the


appropriate sequence.

60
Copyright © 2021, ABES Engineering College
List Example

 In this example a variable named list


example has been created and three
elements have been assigned.

 As we have enclosed elements in


square brackets, this makes list
example is of type list.

61
Copyright © 2021, ABES Engineering College
Ordered Property of List

 Ordered sequence of the list means the


order in which elements appear is unique

 The position of every element is fixed.

 If we change the position of any element,


then list would not be the same anymore.

62
Copyright © 2021, ABES Engineering College
Creation of List

List can be created by many ways as follows.

Creation of Empty List Creation of Non Empty List

63
Copyright © 2021, ABES Engineering College
Accessing the List

Indexing the List


 In the list index are started from 0, it means first element takes 0 index and it increases like
0,1,2…(n-1).
 List also supports negative indexing.

 It means last element can be accessed using -1 index, second last as -2 and so on.

64
Copyright © 2021, ABES Engineering College
Slicing

 Slicing is used to get substring from a string.


 We use Slice operator in the list to get a sub list.

Start= Optional argument by default value


is 0.
End = Optional argument by default value is
number of elements in the list. If any
number given, then value is taken as
number-1.
Step=Options argument by default value is
1.
Colon 1: Required
Colon 2: Optional

65
Copyright © 2021, ABES Engineering College
Slicing Example

 Single colon[:]- It is used to print the entire list.

 Double colon[:]- It is used to print the entire list.

 l[2::]-It is used to print the list starting from index 2 till


the last element of the list.

 L[2:5:]- We have set start and end both as 2 and 5,


so it’s starting from 2 and ending with (5-1) and
printing values for indexes 2,3 and 4 index.

 L[2:5:2]-end and step has been set as 2,5 and 2. So


output substring starting from index 2, ending with 5-
1=4 and step counter is 2, so its skipping alternate
element.
66
Copyright © 2021, ABES Engineering College
Examples of List Slicing

Operator Explanation Example

[:] This gives a complete original list

[1:3] It starts with 1th index and ending


with (3-1=2) index

[2:] Sub list starts with index 2 and


ends at last element as nothing
specified on right side of the
colon

67
Copyright © 2021, ABES Engineering College
Examples of List Slicing

Operator Explanation Example

[1:4:] Start=1, stop=4 and by default


step=1.

[1:4:2] Start=1, stop=4 and by step=2.


As the step is 2, it took every 2nd
element.
[::-1] Starting is 0th index and stopping
at last index and step is negative
count so that it would print in
reverse order

68
Copyright © 2021, ABES Engineering College
Updation in List:

 List updating involves insertion of new elements, deletion of elements or deletion of complete list.

 List is a mutable sequence it means it allows changes in the elements of list.

69
Copyright © 2021, ABES Engineering College
Updation in List:

 List updating involves insertion of new elements, deletion of elements or deletion of complete
list.

 List is a mutable sequence it means it allows changes in the elements of list.

70
Copyright © 2021, ABES Engineering College
Can you answer these Questions

1.What is the output of the following code?

A.[‘XY’,’YZ’]

B.[‘xy’,’yz’]

C. None of the above

D. Both of the above


71
Copyright © 2021, ABES Engineering College
Can you answer these Questions

2.What is the output of the following code?

A. [‘g’,’h’,’k’,’l’,’m’]

B. [‘g’,’h’,’k’,’l’,’m’,9]

C. [‘g’,’h’,’k’,’l’,’m’,8,9]

D. [‘g’,’h’,’k’,’l’,’m’,9,8]

72
Copyright © 2021, ABES Engineering College
Session Plan - Day 4

3.2 List
 Updation in List
 Operations in List
 Built in Methods
 Operations
 Loops
 Nested list
 List Comprehension
 Review Questions
 Practice Exercises

73
Copyright © 2021, ABES Engineering College
Add new element in List:

 We can add elements to the existing list using append function.

 Append function always add the element at the end of the list.

Syntax:

Listname.append (element to be added)

In this example element 5 has been


appended in the originally existed list. It’s
being added in the last

74
Copyright © 2021, ABES Engineering College
Changing new element in List:

 Value of the element at index 3 has been assigned new value as 5, so element in the output
list is changed from 4 to 5.

75
Copyright © 2021, ABES Engineering College
Deletion in List:

List elements can be deleted.

 Using del command If we know the position(index) of the element which is to be deleted.

 We can use the remove method by giving the specific element as given in the example If we know the
position(index) of the element.

76
Copyright © 2021, ABES Engineering College
Deletion in List:

 list1 has been deleted and then we are trying to print it and its giving error because
it does not exist now.

77
Copyright © 2021, ABES Engineering College
Built in Methods in List

Method Remark Example

len() It calculates the length of the list or the


number of elements in the list.

max(list) It returns the maximum element from the list

min(list) It returns a minimum element from the list

list(seq) It converts into any sequence into a list

78
Copyright © 2021, ABES Engineering College
Contd..

Method Remark Example

pop() It deletes the last element from the list


Note – We can also pass index as argument in pop() to
delete a specific index value.

count() It counts the occurrences of a particular element in the list

sort() Sort the elements of the list in ascending order

reverse() Sort the elements of the list in reverse order

79
Copyright © 2021, ABES Engineering College
Operations on List

 Python supports variety of operations on the list

Operation Remark Example

Concatenation Operation adds two list


elements

Repitition It repeats the list specified


number of times

80
Copyright © 2021, ABES Engineering College
Contd..

 Python supports variety of operations on the list

Operation Remark Example

Membership To check whether an element


belongs to the list or not

Membership not I return true of an element

that does not belong to the list

81
Copyright © 2021, ABES Engineering College
Example

 Write Python Program to swap elements in the list.

82
Copyright © 2021, ABES Engineering College
Practice Problems

 Take a list input from user having integer elements and calculate sum and average of the
list.

 Take an input list and swap string elements of the list with empty string.

83
Copyright © 2021, ABES Engineering College
Loops with List

 While loop with list  For Loop with list

84
Copyright © 2021, ABES Engineering College
Example

 Write a python program to print all positive number of a list.

Practice Exercise:

 Write a python program to remove duplicate from the list.

 Write a python program to count positive, negative and string type elements.

85
Copyright © 2021, ABES Engineering College
Nested List

 When we have an element of a list in the form of the list itself, it is called Nested List.

 Elements of the nested list can be accessed using the 2-D indexing access method.

In this example, first [1] denotes [3,4] and second [1] represents 4, so it gives output as 4.

86
Copyright © 2021, ABES Engineering College
Nested List as a Matrix

 We can represent nested list as matrix also.

 For this we would use nested for loop.

 Outer loop would run for number of elements in the list and inner loop would consider
individual element of the nested list as a list.

87
Copyright © 2021, ABES Engineering College
Example

 Create a flat list from a nested list.

.
Practice Exercise:
 Using nested list print transpose, of a given matrix

 Print reverse order of a nested list


.

88
Copyright © 2021, ABES Engineering College
List Comprehensions

 Let's suppose we want to write a program to calculate powers of 3 for a given range.

 Python provide us writing iterative programs in much


 Traditional Programming
lesser lines called List comprehension.

 The same problem has been solved using list


comprehension.

89
Copyright © 2021, ABES Engineering College
List Comprehension

Syntax:
IF ELSE :
[ statements for an item in list ]
 We should notice one change that because in if-else
case output is separated based on the condition.
 We have the facility of adding conditionals in
 if-else and conditions has been written along with
the list comprehension. statements.

90
Copyright © 2021, ABES Engineering College
Session Plan - Day 5

3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises

91
Copyright © 2021, ABES Engineering College
Session Plan - Day 5

3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises

92
Copyright © 2021, ABES Engineering College
Tuple

 Tuple is an immutable (unchangeable) ordered collection of elements of different data types.

 Generally, when we have data to process, it is not required to modify the data values.

 Take an example of week days, here the days are fixed. So, it is better to store the values in the data
collection, where modification is not required.

93
Copyright © 2021, ABES Engineering College
Creation of Tuple

Creation of Empty Tuple Creation of Non Empty Tuple

 Syntax of Creating Non Empty Tuple

 In above example, the () round brackets are used


to create the variable of tuple type.

 We can also call the class to create a tuple object


as shown in example below.

94
Copyright © 2021, ABES Engineering College
Example

 Write a program in python to create one element in tuple

 If you want to create a tuple with single value, it is required to add a comma after the single value as
shown in the above example c=(‘college’,).

 If the comma is not placed, then the single value a= (1) or b=(ABES) will be treated as an
independent value instead of the data collection.
.

95
Copyright © 2021, ABES Engineering College
Packing and Unpacking of Tuple

 Tuple can also be created without using parenthesis; it is known as packing.

 Write a program to create tuple without parenthesis.

In above example 1, newtup4=3,4,5,” hello” creates a new tuple without parenthesis.

96
Copyright © 2021, ABES Engineering College
Unpacking of Tuple

 Write a program to unpack elements in tuple

 Unpacking is called when the multiple variables is assigned to a tuple; then these variables take
corresponding values.

Practice Questions:

 Write a Python program to create the colon of a tuple.


.
 Write a Python program to unpack a tuple in several variables.

97
Copyright © 2021, ABES Engineering College
Accessing Elements in Tuple

 Tuple elements can be accessed using indexes, just like String and List .

 Each element in the tuple is accessed by the index in the square brackets [].

 An index starts with zero and ends with (number of elements - 1)

Example:

Write a program to access index 1 element from tuple.

In above example 1: tuple newtup carries multiple types of data in it as “hello” is string, 2 is integer, and
.
23.45 is float. If we can fetch the index 1 element using print(newtup[1]).

98
Copyright © 2021, ABES Engineering College
Contd…

 Write a program to access index 0 element from tuple.

 Basically, the -1 index will return the last value of tuple.

 Indexes start from zero, and it goes up to a number of elements or say -1.

 Take another example to fetch the -1 index from tuple.

 last element is accessed by print(tuple_days[-1]).


.

99
Copyright © 2021, ABES Engineering College
Indexing in Tuple and Slicing

 Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.

 Write a program to access elements from 0 to 4 index in tuple.

 Write a program to access elements from 1 to 3 index in tuple.

100
Copyright © 2021, ABES Engineering College
Modification/Updating a Tuple

 If we want to change any of the index value in tuple, this is not allowed and throw an error.

 Tuple object does not support item assignment.

 Here, we are taking the same above example of days and showing the immutable
characteristic of tuple

101
Copyright © 2021, ABES Engineering College
Practice Exercises

 Write a Python program to get the 4th element and 4th element from last of a tuple.

 Write a Python program to check whether an element exists within a tuple.

102
Copyright © 2021, ABES Engineering College
Built in Methods in Tuple

Tuple has 2 Built in methods

Method name Remark Example


count() It returns the
occurrences of
the value
given
index() It returns the
index of the
specified value

103
Copyright © 2021, ABES Engineering College
Operations on Tuple

Tuple has some Remarks


Operations operations, which are listed below:
Example

Concatenation Add two tuples

Creates copies of the


Multiplication
tuple

To check whether an
Membership element belong to tuple
or not

Would return true if


. Not Membership element does not belong
to tuple.

104
Copyright © 2021, ABES Engineering College
Loops and Conditions on Tuples

 Tuple can be traversed using Loop

 Take the tuple named tuple_days and print all its elements

 In this example The elements are printed while iterating through for loop condition for in tuple_days and then
we print the values of i in each iteration.

105
Copyright © 2021, ABES Engineering College
Loops and Conditions on Tuples

Example:
 Let have a look to the example where we are placing a condition to return the values
having word length greater than 3.

 In above example , The elements are printed while iterating through for loop condition for in tuple_days
and then we print the values of i in each iteration with the condition if(len(i)>3)

106
Copyright © 2021, ABES Engineering College
Comparison between List and Tuple

List Tuple
Mutable Sequence Immutable Sequence
Accession Slower than Tuple because of Faster access of elements due to
mutable property immutable property
It cannot be used as Dictionary keys Can work as a key of the dictionary
Not suitable for application which needs It suits such scenarios where write
write protection protection is needed.

107
Copyright © 2021, ABES Engineering College
Session Plan - Day 6

3.4 Dictionaries
• Creation
• Assessing
• Modification/Updation
• Nested Dictionary
• Built in Methods
• Review Questions
• Practice Exercises

108
Copyright © 2021, ABES Engineering College
Dictionaries

 Dictionary is a unique data collection of Python which stores the


key-value pair.
 The user can add an element by giving a user-defined index called a key.
 Each key and its corresponding value makes the key-value pair in dictionary.
 This key-value pair is considered as one item in dictionary.

109
Copyright © 2021, ABES Engineering College
Introduction

 In dictionaries, the indexes are not by default. (such as 0 in string,


list, tuple).
 {} is the representation of Dictionary
 Creation of Dictionary
 An empty dictionary can be created as

110
Copyright © 2021, ABES Engineering College
Example-1
 Creating an empty dictionary

111
Copyright © 2021, ABES Engineering College
Example-2
 Creating a non-empty dictionary

112
Copyright © 2021, ABES Engineering College
Accessing of Dictionary
 In dictionary, the items are accessed by the keys.

113
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Output of following code?

A) ‘Java’

B) ‘Python’

C) KeyError

D) None of above

114
Copyright © 2021, ABES Engineering College
Can you answer these questions?

2. Output of following code?

A) 5

B) 10

C) 15

D) None of above

115
Copyright © 2021, ABES Engineering College
Accessing of Dictionary
List Dictionary

By Default indexing User defined Keys

Indexes are only of Keys can be of any


integer type type

Adds an element to Adds an element to


the next default the user defined key
index location

Fetching of element Fetching of value is


is through index, through keys,
lst[0] dic[<key>]

Traversing is easy Traversing is easy


just by increase the just by increase the
index, i+=1 index, i+=1

116
Copyright © 2021, ABES Engineering College
Modification in a Dictionary

117
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Output of following code?

A) {1:’Store’,2:’Kitchen’}

B) {2:’Store’,1:’Kitchen’}

C)KeyError

D) None of above

118
Copyright © 2021, ABES Engineering College
Can you answer these questions?

2. Is it possible to change key in dictionary?

A) True

B) False

119
Copyright © 2021, ABES Engineering College
Nested Dictionary
 As we have the option of a nested list, similarly, dictionaries can consist of
data collections.

120
Copyright © 2021, ABES Engineering College
Session Plan - Day 7

3.4 Dictionary
• Built in Methods in Dictionary
• Loops in Dictionary
• Review Questions
• Practice Exercises

121
Copyright © 2021, ABES Engineering College
Built-in Methods in Dictionary
Method Description

copy() Copying a dictionary to another dictionary

fromkeys() Create a new dictionary with key in a data sequence list/tuple with value

get() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a KeyError.
items() this will return the key-value pair as an output.

keys() this will return only the keys as an output.

values() this will return only the dictionary values as an output.

update() this adds the one dictionary with another dictionary.

pop() The pop() method takes an argument as the dictionary key, and deletes the item from the dictionary.

popitem() The popitem() method retrieves and removes the last key/value pair inserted into the
dictionary.
122
Copyright © 2021, ABES Engineering College
copy()
 copy() method provide a fresh copy with different memory location.

Output

123
Copyright © 2021, ABES Engineering College
fromkey()

Output

124
Copyright © 2021, ABES Engineering College
get()

Output

125
Copyright © 2021, ABES Engineering College
items(),keys(),values()

Output

126
Copyright © 2021, ABES Engineering College
update()

Output

127
Copyright © 2021, ABES Engineering College
pop(),popitem()

Output

128
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Output of following code?

A) {1:1,2:4,3:9,4:16,5:25,6:36}

B) {1:1,2:4,3:9,4:16,5:25}

C) [1,4,9,16,25]

D) Error

129
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Output of following code?

A) {1:’Store’,2:’Kitchen’}

B) {2:’Store’,1:’Kitchen’}

C)KeyError

D) None of above

130
Copyright © 2021, ABES Engineering College
Session Plan - Day 8

3.5 Set
• Creation
• Assessing
• Modification
• Built in methods
• Operators
• Loops
• Frozen Set
• Review Questions

131
Copyright © 2021, ABES Engineering College
Set

 A set is another data collection data types in python, which stores


unique elements in an unordered way.
 Every element in a set is unique and immutable(unchangeable),
i.e. no duplicate values should be there, and the values can’t be
changed.

132
Copyright © 2021, ABES Engineering College
Creation of empty Set

133
Copyright © 2021, ABES Engineering College
Creation of non-empty Set

134
Copyright © 2021, ABES Engineering College
Creation of non-empty Set

135
Copyright © 2021, ABES Engineering College
Can you answer these questions?

2. Is it possible to create an empty set using like s1={} ?

A) True

B) False

136
Copyright © 2021, ABES Engineering College
Accessing set

 Python set’s item cannot be accessed using indexes.

137
Copyright © 2021, ABES Engineering College
Built-in Methods in Dictionary
Method Description

copy() Copying a set to another set

clear() Removes all element from set

add() Adding a new item in set

update() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a Key Error.
remove() to remove the specified element from the given set.

pop() used to removes a random element from the set and returns the popped (removed) elements.

remove () used to remove the specified element from the given set.

discard () used to remove the specified item from the given input set. the remove() method will give an error if
the specified item does not exist but this method will not.

138
Copyright © 2021, ABES Engineering College
copy()
 copy() method provide a fresh copy with different memory location.

139
Copyright © 2021, ABES Engineering College
clear()

140
Copyright © 2021, ABES Engineering College
add()

141
Copyright © 2021, ABES Engineering College
update()

142
Copyright © 2021, ABES Engineering College
remove()

143
Copyright © 2021, ABES Engineering College
discard()

144
Copyright © 2021, ABES Engineering College
Operators
Set Operation Description Operator Method

Union All unique elements in set1 and set2 | union()

Intersection Elements present in set1 and set2 & intersection()

Difference Elements that are present in one set, but not the other - difference()

Symmetric Difference Elements present in one set or the other, but not both ^ symmetric_difference()

Disjoint True if the two sets have no elements in common None isdisjoint()
True if one set is a subset of the other (that is, all
Subset <= issubset()
elements of set2 are also in set1)

True if one set is a subset of the other,


Proper Subset < None
but set2 and set1 cannot be identical

True if one set is a superset of the other (that


Superset >= issuperset()
is, set1 contains all elements of set2)

True if one set is a superset of the other,


Proper Superset > None
but set1 and set2 cannot be identical

145
Copyright © 2021, ABES Engineering College
Union

146
Copyright © 2021, ABES Engineering College
Intersection

147
Copyright © 2021, ABES Engineering College
Intersection

148
Copyright © 2021, ABES Engineering College
Set Difference

149
Copyright © 2021, ABES Engineering College
Symmetric Difference

150
Copyright © 2021, ABES Engineering College
Loops with set

151
Copyright © 2021, ABES Engineering College
Frozen Set

A frozen set is a special category of the set which is unchangeable once created

152
Copyright © 2021, ABES Engineering College
Frozen Set

153
Copyright © 2021, ABES Engineering College
Summary
List Tuple Set Dictionary
List is a collection of values Tuple is ordered and Set stores the unique values Dictionary is a collection of
that is ordered. unchangeable collection of as data collection key-value pairs
values
Represented by [ ] Represented by ( ) Represented by { } Represented by { }
Duplicate elements allowed Duplicate elements allowed Duplicate elements not Duplicate keys not allowed, in
allowed dictionary values allowed
duplicate
Values can be of any type Values can be of any type Values can be of any type Keys are immutable type, and
value can be of any type
Example: Example: Example: Example:
[1, 2, 3, 4] (1, 2, 3, 4) {1, 2, 3, 4} {1:1, 2:2, 3:3, 4:4}
List is mutable Tuple is immutable Set is mutable Dictionary is mutable

List is ordered Tuple is ordered Set is unordered Dictionary is insertion ordered

Creating an empty list Creating an empty Tuple Creating a set Creating an empty dictionary
l=list() t = tuple () s=set () d=dict( )
l = [] t=( ) d={}

154
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Which of the following Python code will create a set?


(i) set1=set((0,9,0))
(ii) set1=set([0,2,9])
(iii) set1={}

A) iii
B) i and ii
C) ii and iii
D) All of Above

155
Copyright © 2021, ABES Engineering College
Can you answer these questions?

2. What is the output of following code?


set1=set((0,9,0))
print(set1)

A) {0,0,9}
B) {0,9}
C) {9}
D) Error

156
Copyright © 2021, ABES Engineering College
Can you answer these questions?

3. What is the output of following python code?


set1={1,2,3}
set1.add(4)
set1.add(4)
print(set1)
A) {1,2,3}
B) {1,2,3,4}
C) {1,2,3,4,4}
D) Error

157
Copyright © 2021, ABES Engineering College

You might also like