0% found this document useful (0 votes)
19 views143 pages

Python Collections: Lists, Strings, Tuples, Dictionaries, Sets

Uploaded by

tvgkp382
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)
19 views143 pages

Python Collections: Lists, Strings, Tuples, Dictionaries, Sets

Uploaded by

tvgkp382
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

3.

Python Collections and Sequences


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
Topics Covered

Day 1 Day 2 Day 3 Day 4

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
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
• Built in Conditions • Built in
Methods methods
• Operations • Operators
• Loops
• Frozen set

5
Session Plan - Day 1

3 Introduction to Python Collections and Sequences


1. String
▪ Creation of String
▪ Assessing of String
▪ Updation of String
▪ Examples
▪ Review Questions

6
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
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
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
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
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
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
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
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
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
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
Syntax of String Slicing

❑ Start index: Index from


which slicing starts.

❑ End Index: Index up to


which slicing end.

❑ Step value is optional.

17
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
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
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
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
Comparison

22
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
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
Contd..
2. What will be the output of the following code Comparison?

A. True
False

B. False
False

25
Contd..
3. What will be the output of the following code snippet?

A. ES

B. En

C. ES En

D. ESEn

26
Contd..
4. What will be the output of the following code snippet?

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

27
Session Plan - Day 2

1. String
▪ Built in Methods
▪ Basic Operations
▪ String Formatters
▪ Loops with Strings
▪ Review Questions
▪ Practice Exercises

28
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
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
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
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
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
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
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
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
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
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
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
Operations in String:
Method Name Explanation Code Snippet

Not in It's reverse of Membership

40
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
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
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
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
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
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
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
String Format()

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


following example, as shown in figure.

48
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
Format Specifiers

Format Specifier Explanation Example

b Use for Binary

o Use for Octal

X or x Use for Hexadecimal

50
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
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
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
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
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
Loops with Strings:

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

56
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
Session Plan - Day 3

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

58
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
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,
[Link] as integer, marks as float,
father’s name as string.

❑ To contain this record list is the


appropriate sequence.

60
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
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
Creation of List

List can be created by many ways as follows.

Creation of Empty List Creation of Non Empty List

63
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
Slicing Example

❑ Single colon[:]- It is used to print the entire list. This im ag


e can
not curr en
t l ybedisplayed
.

❑ 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[Link]- 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[Link]-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
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
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
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
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
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
Can you answer these questions?

1. What will be the Output of the following code?

A.[0,1,2,3,4,5]

B.[0,1,2,3,4,5,6]

C.[0,1,2,3]

D. None of the Above

91
Can you answer these questions?

2. What will be the Output of the following code?

A. [5,7,9]

B.[3,4,5]

C.[6,7,8]

. D.[9,10,11]

92
Session Plan - Day 5

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

93
Session Plan - Day 5

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

94
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.

95
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.

96
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.
.

97
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.

98
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.

99
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]).

100
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]).


.

101
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.

102
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

103
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.

104
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

105
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.

106
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.

107
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)

108
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.

109
Practice Exercises:

Exercise: Write Python program to join two input tuples, if their first element is common.

110
Session Plan - Day 6

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

111
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.

112
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

113
Example-1
▪ Creating an empty dictionary

114
Example-2
▪ Creating a non-empty dictionary

115
Accessing of Dictionary
➢ In dictionary, the items are accessed by the keys.

116
Can you answer these questions?

1. Output of following code?

A) ‘Java’

B) ‘Python’

C) KeyError

D) None of above

117
Can you answer these questions?

2. Output of following code?

A) 5

B) 10

C) 15

D) None of above

118
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

119
Modification in a Dictionary

120
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

121
Can you answer these questions?

2. Is it possible to change key in dictionary?

A) True

B) False

122
Nested Dictionary
➢ As we have the option of a nested list, similarly, dictionaries can consist of
data collections.

123
Session Plan - Day 7

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

124
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.
125
copy()
➢ copy() method provide a fresh copy with different memory location.

Output

126
fromkey()

Output

127
get()

Output

128
items(),keys(),values()

Output

129
update()

Output

130
pop(),popitem()

Output

131
Loops and conditions on dictionaries
➢ Loops and conditions can easily apply to dictionaries.
dict1={1:1,2:4,4:8,6:36}

for key in [Link](): for val in [Link](): for item in [Link](): for i,j in [Link]():
print(key) print(val) print(item) print(i,":",j)

OUTPUT
1 1 (1,1) 1:1
2 4 (2,4) 2:4
4 8 (4,8) 4:8
6 36 (6,36) 6:36

132
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

133
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

134
Session Plan - Day 8

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

135
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.

136
Creation of empty Set

137
Creation of non-empty Set

138
Creation of non-empty Set

139
Can you answer these questions?

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

A) True

B) False

140
Accessing set

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

141
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.

142
copy()
➢ copy() method provide a fresh copy with different memory location.

143
clear()

144
add()

145
update()

146
remove()

147
pop()

148
update()

149
remove()

150
discard()

151
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

152
Union

153
Intersection

154
Intersection

155
Set Difference

156
Symmetric Difference

157
Loops with set

158
Frozen Set

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

159
Frozen Set

160
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={}

161
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

162
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

163
Can you answer these questions?

3. What is the output of following python code?


set1={1,2,3}
[Link](4)
[Link](4)
print(set1)
A) {1,2,3}
B) {1,2,3,4}
C) {1,2,3,4,4}
D) Error

164

You might also like