0% found this document useful (0 votes)
26 views

Data STR - Notes

The document provides information about lists in Python. It discusses defining lists, accessing values in lists using indexes and slicing, deleting values from lists using methods like del, remove(), pop(), clear(), updating lists by assigning new values or using methods like append(), extend(), insert(), and built-in functions and methods for lists like len(), sorted(), insert(), reverse() etc. It also compares lists with tuples, noting that lists are mutable while tuples are immutable.

Uploaded by

Sneha Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Data STR - Notes

The document provides information about lists in Python. It discusses defining lists, accessing values in lists using indexes and slicing, deleting values from lists using methods like del, remove(), pop(), clear(), updating lists by assigning new values or using methods like append(), extend(), insert(), and built-in functions and methods for lists like len(), sorted(), insert(), reverse() etc. It also compares lists with tuples, noting that lists are mutable while tuples are immutable.

Uploaded by

Sneha Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Subject: Programming with Python

Unit 3: Data Structures in Python (14 Marks )


1.1 List
1.2 Tuples
1.3 Sets
1.4 Dictionaries

List in Python:
3.1.1 Defining lists,
accessing values in list,
deleting values in list,
updating lists.
3.1.2 Basic List Operations
3.1.3 Built - in List functions

List in Python:
�The most basic data structure in Python is the sequence.
�Each element of a sequence is assigned a number – its position or index.
�The first index is zero, the second index is one, and so forth.
�Python has six built-in types of sequences(strings, Unicode strings, lists, tuples, buffers, and
xrange objects.) , but the most common ones are lists and tuples.
�There are certain things you can do with all sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership.
� In addition, Python has built-in functions for finding the length of a sequence and for finding
its largest and smallest elements.

List in Python: Defining Lists


�The list is a most versatile data type available in Python which can be written as a list of
comma-separated values(items) between square brackets.
� Important thing about a list is that items in a list need not be of the same type.
�Example
�list1 = ['physics', 'chemistry', 1997, 2000];
�list2 = [1, 2, 3, 4, 5 ];
�list3 = ["a", "b", "c", "d"]
� In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ],separated by commas.

List in Python: Defining Lists


� It can have any number of items and they may be of
different types (integer, float, string etc.).
# empty list
�my_list = [ ]
# list of integers
�my_list = [1, 2, 3]
# list with mixed datatypes
�my_list = [1, "Hello", 3.4]
�Also, a list can even have another list as an item. This is
called nested list.
# nested list
�my_list = ["mouse", [8, 4, 6], ['a']]

List in Python: Accessing values in List


�There are various ways in which we can access the elements of a list.
�We can use the index operator [ ] to access an item in a list.
� Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
�Trying to access an element other that this will raise an
IndexError.
�The index must be an integer.
�We can't use float or other types, this will result into
TypeError.
�Nested list are accessed using nested indexing.
�A list may also contain tuples or so.

List in Python: Accessing values in List


my_list = ['p','r','o','b','e']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: o
print(my_list[4]) # Output: e
# Error! Only integer can be used for indexing
my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
print(n_list[0][1]) # Output: a
print(n_list[1][3]) # Output: 5

List in Python: Negative indexing


my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])

List in Python: Deleting Values in Lists


�We can delete one or more items from a list using the keyword del.
� It can even delete the list entirely.
�my_list = ['p','r','o','b','l','e','m']
�del my_list[2] # delete one item
�print(my_list) # Output: ['p', 'r', 'b', 'l', 'e', 'm']
�del my_list[1:5] # delete multiple items
�print(my_list) # Output: ['p', 'm']
�del my_list # delete entire list
�print(my_list) # Error: List not defined
List in Python: Deleting Values in Lists
�We can use remove() method to remove the given itemor pop() method to remove an item at
the given index.
�The pop() method removes and returns the last item if index is not provided.
�This helps us implement lists as stacks (first in, last out data structure).
�We can use pop() with negative or null index.
�We can also use the clear() method to empty a list.

List in Python: Deleting Values in Lists


�my_list = ['p','r','o','b','l','e','m']
�my_list.remove('p')
�print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
�print(my_list.pop(1)) # Output: 'o'
�print(my_list) # Output: ['r', 'b', 'l', 'e', 'm']
�print(my_list.pop()) # Output: 'm'
�print(my_list) # Output: ['r', 'b', 'l', 'e']
�my_list.clear()
�print(my_list) # Output: []

List in Python: Deleting Values in Lists


# programming languages list
languages = ['Python','Java','C++','French','C']
# remove and return the 4th item
return_value = languages.pop(3)
print('Return Value:', return_value)
# Updated List
print('Updated List:', languages)

List in Python: Deleting Values in Lists


�Finally, we can also delete items in a list by assigning
an empty list to a slice of elements.
>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = [ ]
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = [ ]
>>> my_list
['p', 'r', 'm']

List in Python: Slicing Lists


�We can access a range of items in a list by using the slicing operator : (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])

List in Python: Updating Lists


� List are mutable, meaning, their elements can be changed unlike string or tuple.
�We can use assignment operator (=) to change an item or a range of items.
odd = [2, 4, 6, 8]
odd[0] = 1 # change the 1st item
print(odd) # Output: [1, 4, 6, 8]
odd[1:4] = [3, 5, 7] # change 2nd to 4th items
print(odd) # Output: [1, 3, 5, 7]
List in Python: Updating Lists
�We can add one item to a list using append() method
�And add several items using extend() method.
�Examlple
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)

List in Python: Updating Lists


�We can also use + operator to combine two lists. This is also called concatenation.
�The * operator repeats a list for the given number of times.
�Example
odd = [1, 3, 5]
print(odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output: ["re", "re", "re"]

List in Python: Updating Lists


�Furthermore, we can insert one item at a desired location by using the method insert() or insert
multiple items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
print(odd) # Output: [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) # Output: [1, 3, 5, 7, 9]

List in Python: Basic List Operation


� 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.
� In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.
Python Expression Results Description Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'HI!’, ‘HI!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: 123 Iteration
print x,

List in Python: Built-in Functions


Sr. Function Description
1 cmp(list1, list2) Compares elements of both lists. (Works only in Python 2.x)
2 len(list) Gives the total length of the list.
3 max(list) Returns item from the list with max value.
4 min(list) Returns item from the list with min value.
5 list(seq) Converts a tuple into list.
6 sum(list) Display sum of all elements in list
7 Sorted(list) It returns a sorted version of the list, but does not change the
original one.
8 any(list) It returns True if even one item in the Python list has a True
value.
9 all(list) It returns True if all items in the list have a True value.

List in Python: Built-in Methods


Sr.No. Methods Description
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort() Sorts objects of list, use compare func if given
10 New=old.copy() Shallow copy the new list
11 List.clear() It empties the Python list.

Tuple in Python:
3.2.1 Defining Tuples,
accessing values in Tuples,
deleting values in Tuples,
updating Tuples.
3.2.2 Basic Tuple Operations
3.2.3 Built - in Tuple functions
# Difference between List & Tuple

# Difference between List & Tuple:


S.NO List Tuple
1 The literal syntax of List is shown by the The literal syntax of the tuple is shown by
[]. the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable length The tuple has the fixed length
4 The List provides more functionality than The tuple provides less functionality than
tuple. the Tuple.
5 The List is used in the scenario in which we The tuple is used in the cases where we
need to store the simple collections with no need to store the read-only collections
constraints where the value of the items can i.e., the value of the items can not be
be changed. changed. It can be used as the key inside
the dictionary
6 Lists have several built-in methods Tuple does not have must built-in
methods. compared to the list
7 List consume more memory Tuple consume less memory as compared to
list

Tuple in Python: Defining Tuple


�The Tuple is a data type available in Python which can be written as a collection of comma-
separated values (items) between rounded brackets (Paranthesis).
� Items in a Tuple need not be of the same type.
�Example
�Tup=( ) #Empty Tuple
�Tuple1 = ('physics', 'chemistry', 1997, 2000)
�Tuple2 = (1, 2, 3, 4, 5 )
�Tuple3 = ("a", "b", "c", "d“)
�In Python programming, a Tuple is created by placing all the items (elements) inside a
round bracket ( ), separated by commas.

Tuple in Python: Defining Tuples


� It can have any number of items and they may be of different types (integer, float, string etc.).
# empty Tuple
�my_Tuple =( )
# Tuple of integers
�my_Tuple = (1, 2, 3)
# Tuple with mixed datatypes
�my_Tuple = (1, "Hello", 3.4)
�Also, a Tuple can even have another Tuple as an item. This is called nested Tuple.
# nested Tuple
�My_t=(1,"kkwp", 12.36, 'a',(1,2,3), 78)

Tuple in Python: Accessing values in Tuple


�There are various ways in which we can access the elements of a Tuple.
�We can use the index operator [ ] to access an item in a Tuple.
� Index starts from 0. So, a Tuple having 5 elements will have index from 0 to 4.
�Trying to access an element other that this will raise an
IndexError.
�The index must be an integer.
�We can't use float or other types, this will result into
TypeError.
�Nested Tuple are accessed using nested indexing.
�A Tuple may also contain tuples or so.
Tuple in Python: Accessing values in Tuple
�Note:
1. TypeError:
If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The
index must always be an integer.
2. IndexError:
Index out of range. This error occurs when we mention the index which is not in the range. For
example, if a tuple has 5 elements and we try to access the 7th element then this error would
occur.

Tuple in Python: Accessing values in Tuple


my_Tuple = ('p','r','o','b','e„)
print(my_Tuple[0]) # Output: p
print(my_Tuple[2]) # Output: o
print(my_Tuple[4]) # Output: e
# Error! Only integer can be used for indexing
my_Tuple[4.0]
# Nested Tuple
n_Tuple = ("Happy", (2,0,1,5))
# Nested indexing
print(n_Tuple[0][1]) # Output: a
print(n_Tuple[1][3]) # Output: 5

Tuple in Python: Slicing Tuples


�We can access a range of items in a Tuple by using the
slicing operator : (colon).
my_Tuple = ('p','r','o','b','l','e','m')
# elements 3rd to 5th
print(my_Tuple[2:5]) Output:['o', 'b', 'l']
# elements 6th to end
print(my_Tuple[5:]) Output:['e', 'm']

Tuple in Python:
�Tuple with only single element:
�Note: When a tuple has only one element, we must put a comma after the element, otherwise
Python will not treat it as a tuple.
�# a tuple with single data item
my_data = (99,)
If we do not put comma after 99 in the above example then
python will treat my_data as an int variable rather than a tuple.

Tuple in Python: Negative indexing


my_Tuple = ('p','r','o','b','e„)
# Output: e
print(my_Tuple[-1])
# Output: p
print(my_Tuple[-5])
Tuple in Python: Negative indexing
◻ str1=['p','r','o','b','l','e','m']
◻ print(str1[-5:-2:1]);
◻ output-['o', 'b', 'l'] Step plus
◻ print(str1[-5:-2:-1]);
◻ output-[] no selection
◻ print(str1[-5:-7:-1]);
◻ output-['o', 'r'] Step plus
Tuple in Python: Deleting Values in Tuples
�Removing individual tuple elements is not possible in
tuple.
�We can use another tuple with the undesired elements
discarded.
�To explicitly remove an entire tuple, just use the del
statement.
�For example −
tup = ('physics', 'chemistry', 1997, 2000)
del tup;

Tuple in Python: Updating Tuples


�Unlike lists, tuples are immutable.
�This means that elements of a tuple cannot be changed
once it has been assigned.
�But, if the element is itself a mutable datatype like list,
its nested items can be changed.
�We can also assign a tuple to different values
(reassignment).
t3=(1,2,[4,5,6],7)
t3[2][1]=11
print(t3)
(1, 2, [4, 11, 6], 7)

Tuple in Python: Basic Tuple Operation


�Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except that
the result is a new Tuple, not a string.
� In fact, Tuples respond to all of the general sequence
operations we used on strings in the prior chapter.

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!„)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!„) Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration

Tuple in Python: Updating Tuples


�Example
odd = (1, 3, 5)
print(odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output: ["re", "re", "re"]
t3=(1, 2, [4, 11, 6], 7)
t4=t3+(5,6)
Print(t4) #O/P (1, 2, [4, 11, 6], 7, 5, 6)
t4=t3+[55,66]
Trace back (most recent call last): File "<pyshell>", line 1, in <module> Type Error: can only
concatenate tuple (not "list") to tuple

Tuple in Python: Built-in Functions


Sr.No. Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is
greater than tuple2 otherwise false.
(Only for Python Version 2.X)
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple.
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
6 sum(tuple) Returns sum of all elements in tuple
7 any(tuple) Return true if any value in tuple is greater than one
8 all(tuple) Return true if all values in tuple are greater than one

Tuple in Python: Built-in Functions


�Example
>>> t=(8,7,1,2,3,9,4,5,6)
>>> t
(8, 7, 1, 2, 3, 9, 4, 5, 6)
>>> len(t)
9
>>> min(t)
1
>>> max(t)
9
>>> sorted(t)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(t)
45
�Example
>>> any(t)
True
>>> all(t)
True
>>> l=[2,3,4,5,2,3,4,5]
>>> t1=tuple(l)
>>> t1
(2, 3, 4, 5, 2, 3, 4, 5)
>>> l
[2, 3, 4, 5, 2, 3, 4, 5]

Tuple in Python: Built-in Methods


Sr.No. Methods Description
1 Tuple.count(obj) Returns count of how many times obj occurs
in Tuple
>>> t=(1,2,3,4,1,6,1)
>>> t.count(1)
3

2 Tuple.index(obj) Returns the lowest index in Tuple that obj


appears
>>> t=(1,2,3,4,1,6,1)
>>> t.index(6)
5

Sets in Python:
3.2.1 Defining Sets,
accessing values in Sets,
deleting values in Sets,
updating Sets.
3.2.2 Basic Set Operations
3.2.3 Built - in Set functions
# Difference between List, Tuple and set
# Advantages/features of sets

Sets in Python:
�The set in python can be defined as the unordered collection of various items enclosed within
the curly braces i.e. { }.
�The elements of the set can not be duplicate.
�The Set is mutable but elements of set must be immutable.
�However, the set itself is mutable. We can add or remove items from it.
�Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
�Unlike other collections in python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index.
�However, we can print them all together or we can get the list of elements by looping through
the set.

Sets in Python:
�Mathematically a set is a collection of items not in any particular order.
�A Python set is similar to this mathematical definition with below additional conditions.
�The elements in the set cannot be duplicates.
�The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
�There is no index attached to any element in a python set.
�So they do not support any indexing or slicing operation.

Sets in Python: Creating set


�A set is created by placing all the items (elements) inside curly braces {}, separated by
comma.
E.g. set1={76,”kkwp”,‟a‟,21.30}
�or by using the built-in function set().
�E. g.
set2=set([45,67,23,90])
OR
set3=set((45,67,23,90))
OR
set4=set({45,67,23,90})
�set() function allows only one parameter that may be single element to be added or a list, a
tuple or a set.

Sets in Python: Creating set


�Sets can have any number of items and they may be of different types (integer, float, tuple,
string etc.).
�But a set cannot have a mutable element, like list, set or dictionary, as its element.
�E. g.
set2={[34,67,12]} //Not allowed
But following is allowed
String = ‘hello’
set1 = set(String)
print(set1)
{'o', 'h', 'l', 'e’} #Output

Sets in Python: Creating Sets


�A set contains only unique elements but at the time of set creation, multiple duplicate values
can also be passed.
�Order of elements in a set is undefined and is unchangeable.
E.g
>>> b={3,2,1,2,2,3,1,1,3,2}
>>> b
{1, 2, 3}
OR
>>> set4=set({45,67,23,90})
>>> set4
{90, 67, 45, 23}

Sets in Python: Adding elements in Sets


�We can add elements to a set by using add() method.
�Again as discussed there is no specific index attached to the
newly added element.
�>>> b={3,2,1,2}
�>>> b.add(5,6) //multiple elements not allowed
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
�>>> b.add(5)
�>>> b
�{1, 2, 3, 5}

Sets in Python: update elements in Sets


�For addition of two or more elements Update() method is used.
�The update() method accepts lists, strings, tuples as well as other sets as its arguments.
� In all of these cases, duplicate elements are avoided.
�Sets are mutable. But since they are unordered, indexing have no meaning.
�We cannot access or change an element of set using indexing or slicing. Set does not support
it.
E. g.
Months=set(["January","February", "March", "April", "May", "June"
])
Months.update(["July","August","September","October"])

Sets in Python: Delete elements in Sets


�Because a set isn‟t indexed, you can‟t delete an elementusing its index.
�So for this, you must use either discard() or remove() method.
�A method must be called on a set, and it may alter the set.
�A particular item can be removed from set using methods,
discard() and remove().
�The only difference between the two is that:
�while using discard() if the item does not exist in the set, it
remains unchanged.
�But remove() will raise an error in such condition i.e. a
KeyError arises if element doesn‟t exist in the set.

Sets in Python: Delete elements in Sets


Months=set(["January","February","March","April","May"])
Months.discard(“May”)
print(Months)
{'March', 'February', 'June', 'January', 'April‟} //O/P
Months.discard(“May”)
print(Months)
{'March', 'February', 'June', 'January', 'April‟} //O/P
Months.remove(“May”)
print(Months)
Traceback (most recent call last):
File "H:\Python\setseg.py", line 17, in <module>
Months.remove(“May’’)
KeyError: ‘May’

Sets in Python: Accessing elements in Sets


�Set items cannot be accessed by referring to an index, since sets
are unordered the items has no index.
�But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword.
(Use Membership Operator) s={1,2,3,4}
set1={56,34,12,89,59,90} for i in s:
print(set1)
{34, 12, 56, 89, 90, 59} if i==2:
for s in set1:
print(s, end=",") print("yes")
#O/P
print(i, end=",")
34,12,56,89,90,59,
else:

print("sorry")

#O/P

1,yes

2,3,4,sorry

Sets in Python: Built-in Methods


Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do
nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
remove() Removes an element from the set. If the element is not a
member, raise a Key Error

Sets in Python: Built-in Methods


Method Description
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitary set element. Raise
KeyError if the set is empty
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and
another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others

Sets in Python: Built-in Methods


15
set1={56,34,12,89,59,90}
set1.clear()
print(set1)
set()
_________________________________________________
set1={56,34,12,89,59,90}
set2=set1.copy()
print(set2)
{34, 56, 89, 90, 59, 12}.
_________________________________________________
set2.pop()
34
print(set2)
{56, 89, 90, 59, 12}
set1={56, 89, 90, 59}
set2={1,2,3,34}
print(set1.isdisjoint(set2))
True
set3={1,2,3,90}
print(set1.isdisjoint(set3))
False
__________________________________________________
Set1={56, 89, 90, 59}
Set2={1, 2, 3}
Set3={1, 2, 3, 90}
print(set2.issubset(set3))
True
print(set3.issuperset(set2))
True
print(set3.issubset(set2))
False

Sets in Python: Built-in Operations


�Union
�Intersection
�Difference
�Subset
�Check Membership
�Iteration

Sets in Python: Built-in Methods


�difference()
� If A and B are two sets. The set difference of A and B is a set
of elements that exists only in set A but not in B.
�For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
�A - B = {1, 4} and B - A = {9}
�Hence
A.difference(B)
returns A-B
And B.difference(A)
Returns B-A
Sets in Python: Built-in Methods
�difference_update()
The syntax of difference_update() is:
A.difference_update(B)
O/P: A={1,4}
Here, A and B are two sets.
The difference_update() updates set A with the set
difference of A-B.

Sets in Python: Built-in Methods


�intersection()
�The intersection of two or more sets is the set of elements
which are common to all sets. For example:
�A = {1, 2, 3, 4} B = {2, 3, 4, 9} C = {2, 4, 9, 10}
Then, A∩B = B∩A ={2, 3, 4}
�The syntax of intersection() in Python is:
�A.intersection(*other_sets)
�The intersection() allows arbitrary
number of arguments (sets).
E.g. print(C.intersection(A, B))
OR print(A&B&C) is same
for both O/P: {2, 4}

Sets in Python: Built-in Methods


intersection_update()
The syntax of intersection_update() is:
A.intersection_update(*other_sets)
It only updates the set calling the intersection_update()
method.
Suppose,
A.intersection_update(B, C)
When you run the code,
result will be None
A will be equal to the intersection of A, B and C
B remains unchanged
C remains unchanged

Sets in Python: Built-in Methods


A = {1, 2, 3, 4}
B = {2, 3, 4, 9}
C = {2, 4, 9, 10}
print(C.intersection_update(A,B))
None
print(A)
{1, 2, 3, 4}
print(B)
{9, 2, 3, 4}
print(C)
{2, 4}

Sets in Python: Built-in Methods


�symmetric_difference()
� If A and B are two sets. The symmetric difference of A and B is
a set of elements that are uncommon in set A and in set B.
�For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
�Hence
A.symmetric_difference(B)=B.symmetric_difference(A)
returns
(A-B)+(B-A)

Sets in Python: Built-in Methods


�symmetric_difference_update()
�For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
�Hence
A.symmetric_difference_update(B)
returns
A=(A-B)+(B-A)
i.e. {1,4,9}

Sets in Python: Built-in Methods


�union()
� If A and B are two sets. The union of A and B is a set of
elements that exists in set A as well as in B.
�For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
�Hence
A.union(B)
returns
A+B
i.e. {1,2,3,4,9}

Sets in Python: Built-in Functions


Function Description
all() Return True if all elements of the set are true (or if the set is
empty).
any() Return True if any element of the set is true. If the set is
empty, return False.
enumerate() Return an enumerate object. It contains the index and value
of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set (does not
sort the set itself). E.g. sorted(s,reverse=True) will convert
into List
sum() Return the sum of all elements in the set.
Sets in Python:
Built-in Functions –
>>> s1={45,23,78,0,12}
>>> all(s1)
False
>>> any(s1)
True
>>> sorted(s1)
[0, 12, 23, 45, 78]
>>> max(s1)
78
>>> min(s1)
0
>>> sum(s1)
158
>>> len(s1)
5

Sets in Python: Built-in Functions – enumerate()


Syntax:
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
e.g.1
A = {11, 222, 33, 44}
obj1=enumerate(A)
for i in obj1:
print (i);
�Output
(0, 33)
(1, 11)
(2, 44)
(3, 222)

list in Python: Built-in Functions – enumerate()


e.g.2
l1 = ["eat","sleep","repeat"]
obj1 = enumerate(l1)
print ("Return type:",type(obj1))
print (list(enumerate(l1)))
Output
Return type: <class 'enumerate'>
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]

e.g.3
l1 = ["eat","sleep","repeat"]
obj1 = enumerate(l1)
print ("Return type:",type(obj1))
print (list(enumerate(l1,2)))
Output
Return type: <class 'enumerate'>
[(2, 'eat'), (3, 'sleep'), (4, 'repeat')]

Sets in Python: Frozen Sets


�Frozen set is just an immutable version of a Python
set object.
�While elements of a set can be modified at any time,
elements of the frozen set remain the same after
creation.
�While tuples are immutable lists, frozensets are immutable
sets.
�Due to this, frozen sets can be used as keys in Dictionary
or as elements of another set.
�Syntax:
�f_set=frozenset(normal_set)

Sets in Python: Frozen Sets Methods


�This datatype supports methods like
�copy()
�difference()
�intersection()
�isdisjoint()
�issubset()
�issuperset()
�symmetric_difference()
�union().
�Being immutable it does not have method that add or remove elements

Sets in Python: Frozen Sets


>> s1={1,2,3,6,7}
>>> s2=frozenset(s1)
>>> type(s2)
<class 'frozenset'>
>>> s2
frozenset({1, 2, 3, 6, 7})
>>> >>> s2.add(90) #error
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
Attribute Error: 'frozenset' object has no attribute 'add'

# Difference between List & Sets:


S List Set
NO
1 The literal syntax of List is The literal syntax of the set is shown
shown by the [ ]. by the { }.
2 The List is mutable. The set is mutable, but elements of set are
immutable.

3 List is a type of Ordered collection Sets is a type of unordered collection

4 Supports indexing and Slicing Don‟t Supports indexing and Slicing


5 Cant perform operations like Can perform operations like union,
union, intersection and intersection and difference
difference

6 List allows duplicates Duplication not allowed

# Difference between Set & Tuple:


S Set Tuple
NO
1 The literal syntax of the set is shown The literal syntax of the tuple is
by the { }. shown by the ( ).
2 The set is mutable, but elements Of set are The tuple is immutable.
immutable.
3 Sets is a type of variable length The tuple has the fixed length and
and unordered collection ordered collection.
4 Don‟t Supports indexing and Slicing Supports indexing and Slicing
5 Can perform operations like union, Cant perform operations like
intersection and difference union, intersection and
difference

6 Duplication not allowed Tuples allows duplicates

#Advantages of Sets:
�Because sets cannot have multiple occurrences of the
same element, it makes sets highly useful to efficiently
remove duplicate values from a list or tuple and to
perform common math operations like unions and
intersections.
�E.g.
>>> l=[2,3,4,5,2,3,4,5]
>>> s=set() #empty set creation.
>>> s=set(l)
>>> s
{2, 3, 4, 5}

Dictionary in Python:
3.2.1 Defining Dictionary,
accessing values in Dictionary,
deleting values in Dictionary,
updating Dictionary.
3.2.2 Basic Dictionary Operations
3.2.3 Built - in Dictionary functions
# Difference between List, Tuple, set and Dictionary
# Advantages/features of Dictionary
Dictionary in Python:
�A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python
dictionary holds key-value pairs.
�Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element.
�Dictionary holds key:value pair.
�Key value is provided in the dictionary to make it more optimized.
�Dictionaries are optimized to retrieve values when the key is known.
�Note – Keys in a dictionary doesn‟t allows Polymorphism.

Dictionary in Python:
�Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces.
�An empty dictionary without any items is written with just two curly braces, like this: {}.
�Keys are unique within a dictionary while values may not be.
�The values of a dictionary can be of any type, but the keysmust be of an immutable data type
such as strings,numbers, or tuples.
�Note – Dictionary keys are case sensitive, same name but
different cases of Key will be treated distinctly.

Dictionary in Python: Creating Dictionary


� In Python, a Dictionary can be created by placing sequence of elements within curly {}
braces, separated by „comma‟.
�Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its value.
�Values in a dictionary can be of any data type and can be duplicated,
�Dictionary is mutable, whereas keys can‟t be repeated and must be immutable.

Dictionary in Python: Creating Dictionary


Example:
name={1:"KKWP",2:"KKWIEER",3:"KKWPH",4:[45,56,90]}
print(name)
{1: 'KKWP', 2: 'KKWIEER', 3: 'KKWPH', 4: [45, 56, 90]}
6
Empty Dictionary
>>> d={}
>>> type(d)
<class 'dict'>

Dictionary in Python: Creating Dictionary


Using dict() Function
Example:
>>> d1=dict((1,"Nashik")) #one parameter
>>> d1=dict((1,"Nashik"),(2,"Pune")) //2 parameter error
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
TypeError: dict expected at most 1 arguments, got 2
Dictionary in Python: Creating Dictionary
Example:
>>> d1=dict([(1,"Nashik"),(2,"Pune")]) #Passing List as argu.
>>> d1
{1: 'Nashik', 2: 'Pune'}
>>> d1=dict(((1,"Nashik"),(2,"Pune"))) #Passing tuple as argu.
>>> d1
{1: 'Nashik', 2: 'Pune'}
>>> d1=dict({(1,"Nashik"),(2,"Pune")}) #Passing set as argu.
>>> d1
{1: 'Nashik', 2: 'Pune'}

Dictionary in Python: Creating Dictionary


Example:
Using Loop
>>> mydict={x * x : x for x in range(8)}
>>> mydict
{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
>>> D2={1:35,1:12,1:58} # takes last entry
>>> D2
{1: 58}

Dictionary in Python:
Accessing Elements in Dictionary
�While indexing is used with other container types to
access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.
�The difference while using get() is that it
returns None instead of KeyError, if the key is not
found.
�E.g.
>>> my_dict={1:34,2:56,3:89,5:67}
>>> my_dict.get(3)
89
>>> my_dict.get(4)

Dictionary in Python:
Accessing Elements in Dictionary
Example:
>>> my_dict={1:34,2:56,3:89,5:67}
>>> my_dict
{1: 34, 2: 56, 3: 89, 5: 67}
>>> my_dict[2]
56
>>> my_dict[4]
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
KeyError: 4
Dictionary in Python:
Add/Update Elements in Dictionary
�Dictionaries are mutable. We can add new items or change the
value of existing items using assignment operator.
� If the key is already present, value gets updated, else a new
key: value pair is added to the dictionary.
� In Python Dictionary, Addition of elements can be done in
multiple ways. One value at a time can be added to a Dictionary
by defining value along with the key e.g. Dict[Key] = ‘Value’.
�Updating an existing value in a Dictionary can be done by using
the built-in update() method.
�Note- While adding a value, if the key value already exists, the
value gets updated otherwise a new Key with the value is added
to the Dictionary.

Dictionary in Python:
Add/Update Elements in Dictionary
Example:
>>> my_dict={1:34,2:56,3:89,5:67}
>>> my_dict
{1: 34, 2: 56, 3: 89, 5: 67}
>>> my_dict[4]=222 #Add new key:value
>>> my_dict
{1: 34, 2: 56, 3: 89, 5: 67, 4: 222}
>>> my_dict[3]=48 #Update existing value
>>> my_dict
{1: 34, 2: 56, 3: 48, 5: 67, 4: 222}

�# Dictionary with three items


�Dictionary1 = {'A': 'Geeks', 'B': 'For', }
�Dictionary2 = {'B': 'Geeks'}

�# Dictionary before Updation
�print("Original Dictionary:")
�print(Dictionary1)

�# update the value of key 'B'
�Dictionary1.update(Dictionary2)
�print("Dictionary after updation:")
�print(Dictionary1)
Output
Original Dictionary:
{'A': 'Geeks', 'B': 'For'}
Dictionary after updation:
{'A': 'Geeks', 'B': 'Geeks

Dictionary in Python:
Add/Update Elements in Dictionary
Example:
�>>> d={1:23,2:45,5:{4,5,6},8:89}
�>>> d
�{1: 23, 2: 45, 5: {4, 5, 6}, 8: 89}
�>>> d[5]
�{4, 5, 6}
�>>> type(d[5])
�<class 'set'>
�>>> d={1:23,2:45,5:{4:55,5:66,6:77},8:89}
�>>> d
�{1: 23, 2: 45, 5: {4: 55, 5: 66, 6: 77}, 8: 89}
�>>> type(d[5])
�<class 'dict'>

Dictionary in Python:
Add/Update Elements in Dictionary
Example:
�>>> d={1:23,2:45,5:{4,5,6},8:89}
�>>> d
�{1: 23, 2: 45, 5: {4, 5, 6}, 8: 89}
�>>> d[5]
�{4, 5, 6}
�>>> type(d[5])
�<class 'set'>
�>>> d={1:23,2:45,5:{4:55,5:66,6:77},8:89}
�>>> d
�{1: 23, 2: 45, 5: {4: 55, 5: 66, 6: 77}, 8: 89}
�>>> type(d[5])
�<class 'dict'>

Dictionary in Python:
Accessing Elements from Dictionary
Example:
�>>> d={1:23,2:45,5:{4:{12:14,13:15},5:66,6:77},8:89}
�>>> d
�{1: 23, 2: 45, 5: {4: {12: 14, 13: 15}, 5: 66, 6: 77}, 8: 89}
�>>> d[1]
�23
�>>> d[5][5]
�66
�>>> d[5][4][12]
�14

Dictionary in Python:
Delete Elements from Dictionary
� In Python Dictionary, deletion of keys can be done by
using the del keyword.
�Using del keyword, specific values from a dictionary as
well as whole dictionary can be deleted.
� Items in a Nested dictionary can also be deleted by using
del keyword and providing specific nested key and
particular key to be deleted from that nested Dictionary.
�Note- del will delete the entire dictionary and hence
printing it after deletion will raise an Error.

Dictionary in Python:
Delete Elements from Dictionary
Example:
>>>d={1:23,2:45,5:{4:{12:14,13:15},5:66,6:77},8:89}
>>>del d[2]
>>> d
{1: 23, 5: {4: {12: 14, 13: 15}, 5: 66, 6: 77}, 8: 89}
>>> del d[5][5]
>>> d
{1: 23, 5: {4: {12: 14, 13: 15}, 6: 77}, 8: 89}
>>> del d
>>> d
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
NameError: name 'd' is not defined

Dictionary in Python: Built-in Methods


Method Description
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the
given key.
popitem() Removes the arbitrary key-value pair from the dictionary
and returns it as tuple.
get() It is a conventional method to access a value for a key.
values() returns a list of all the values available in a given dictionary.
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict‟s keys
items() Returns a list of dict‟s (key, value) tuple pairs
fromkeys() Create a new dictionary with keys from seq and
values set to value.
update() Adds dictionary dict2‟s key-values pairs to dict

Dictionary in Python: Built-in Methods


Dictionary1={1:‟a‟,2:‟b‟,3:‟c‟}
Dictionary1.clear()
print(Dictionary1)
{}
_________________________________________________
Dictionary1={1:‟a‟,2:‟b‟,3:‟c‟}
Dictionary2=Dictionary1.copy()
print(Dictionary2)
{1:‟a‟,2:‟b‟,3:‟c‟}
_________________________________________________
>>> Dictionary1.pop(2)
'b'
>>> Dictionary1
{1: 'a', 3: 'c'}
>>> Dictionary1.popitem()
(3, 'c')
>>> Dictionary1
{1: 'a'}
__________________________________________________
>>> Dictionary1.values()
dict_values(['a', 'b', 'c'])

Dictionary in Python: Built-in Methods


>>> Dictionary1.setdefault(1,'a„)
>>> Dictionary1.setdefault(4)
>>> Dictionary1
{1: 'a', 2: 'b', 3: 'c', 4: None}
>>> Dictionary1.setdefault(5,'e')
'e'
>>> Dictionary1
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: 'e'}
_________________________________________________
>>>Dictionary1.items()
dict_items([(1, 'a'), (2, 'b'), (3, 'c')])
Dictionary1={1:‟a‟,2:‟b‟,3:‟c‟}
>>> Dictionary1.keys()
dict_keys([1,2,3]
_________________________________________________
�>>> seq=[1,3,5,7]
�>>> d=dict.fromkeys(seq,5)
�>>> d
�{1: 5, 3: 5, 5: 5, 7: 5}
___________________________
>>> Dictionary1
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: 'e'}
�d=dict.fromkeys(Dictionary1,5)
�>>> d
�{1: 5, 2: 5, 3: 5, 4: 5, 5: 5}

Dictionary in Python: Built-in Methods


d = {'x': 2}
d.update(y = 3, z = 0)
print(d)
{'x': 2, 'y': 3, 'z': 0}
Dictionary in Python: Built-in Functions
Function Description
all() Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any() Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
max() Returns Maximum value
min() Returns Minimum value

Dictionary in Python:
Built-in Functions
>>> Dictionary1
{1: 5, 2: 'b', 3: 5, 4: None, 5: 5, 7: 5}
>>> any(Dictionary1)
True
>>> all(Dictionary1)
True
>>> max(Dictionary1)
7
>>> min(Dictionary1)
1
>>> len(Dictionary1)
6
>>> sorted(Dictionary1)
[1, 2, 3, 4, 5, 7]

Dictionary in Python: Built-in Functions


>>> grocery = {1:'bread', 'milk':3, 7:'butter'}
>>> max(grocery)
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'
>>> grocery = {'a':'bread', 'milk':'dfdsf', 'c':'butter'}
>>> max(grocery)
'milk'
>>> grocery = {'x':'bread', 'milk':'dfdsf', 'c':'butter'}
>>> max(grocery)
'x‘
>>> min(grocery)
'c‘
>>> sorted(grocery)
['c', 'milk', 'x']

You might also like