0% found this document useful (0 votes)
6 views28 pages

Module - 4

This document covers the concepts of lists, tuples, sets, and dictionaries in Python, detailing their creation, operations, and built-in functions. It explains list operations such as indexing, slicing, concatenation, and methods for modifying lists, as well as the concepts of mutability, aliasing, and cloning. Additionally, it discusses loops for iterating over lists and the differences between mutable and immutable data types.

Uploaded by

bhuvansm69
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)
6 views28 pages

Module - 4

This document covers the concepts of lists, tuples, sets, and dictionaries in Python, detailing their creation, operations, and built-in functions. It explains list operations such as indexing, slicing, concatenation, and methods for modifying lists, as well as the concepts of mutability, aliasing, and cloning. Additionally, it discusses loops for iterating over lists and the differences between mutable and immutable data types.

Uploaded by

bhuvansm69
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/ 28

MODULE-4

LIST SET, DICTIONARY AND TUPLE

List: Creating a List, List indexing and splitting, Python List Operations, List Built-in functions,

Tuple: Creating a tuple, Indexing, Deleting Tuple, Tuple operations, Tuple inbuilt functions.

Set: Creating a set, Python Set Operations, Python Built-in set methods.

Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the dictionary values, and

adding dictionary values, Iterating Dictionary, Built in Dictionary functions


Lists

List is an ordered sequence of items. Values in the list are called elements / items.

It can be written as a list of comma-separated items (values) between square
brackets[ ].

Items in the lists can be of different data types.


Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

operations examples description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

List slices:

List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]

default start value is 0

default stop value is n-1

[:] this will print the entire list

[2:2] this will create a empty slice
slices example description
a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step
>>> a[0:6:2] size 2.(from index[0] to 2nd
[9, 7, 5] element and from that
>>> a[0:6:3] position to next 2nd element
[9,6]

List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)

syntax example description


1 >>> a=[1,2,3,4,5]
>>> a.append(6) Add an element to
a.append(element) >>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]
2 a.insert(index,element) >>> a.insert(0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>> a.extend(b) Add all elements of a
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returns the index of
a.index(element) >>> a.index(8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sort items in a list in
sum()
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>> a.reverse()
Reverse the order of
a.reverse() >>> print(a)
items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>> a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>> a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>> a.count(6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined

List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.

Iterating over a sequence is called traversal.

Loop continues until we reach the last item in the sequence.

The body of for loop is separated from the rest of the code using indentation.

Syntax:
for val in sequence:

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop

The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

When the condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

Mutability:

Lists are mutable. (can be changed)

Mutability is the ability for certain types of data to be changed without entirely
recreating it.

An item can be changed in a list by accessing it directly as part of the assignment
statement.

Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.
Example description
changing single element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

Aliasing(copying):

Creating a copy of a list is called aliasing.


When you create a copy both the list will be having same memory location.

changes in one list will affect another list.

Alaising refers to having different names for same list values.

Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]


In this a single list object is created and modified using the subscript operator.

When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.

This type of change is what is known as a side effect. This happens because after
the assignment b=a, the variables a and b refer to the exact same list object.

They are aliases for the same object. This phenomenon is known as aliasing.

To prevent aliasing, a new object can be created and the contents of the original
can be copied which is called cloning.

Clonning:
❖ To avoid the disadvantages of copying we are using cloning.
❖ Creating a copy of a same list of elements with two different memory locations is called cloning.


Changes in one list will not affect locations of aother list.

Cloning is a process of making a copy of the list without modifying the original list.

1. Slicing
2. list()method
3. copy() method

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method

a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List as parameters:

In python, arguments are passed by reference.

If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.

When a list to a function is passed, the function gets a reference to the list.

Passing a list as an argument actually passes a reference to the list, not a copy of the list.

Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)

Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)

Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:

A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.

A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to
a tuple or remove elements from the tuple.

But tuple can be converted into list and list can be converted in to tuple.
methods example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:

Tuples are faster than lists.

If the user wants to protect the data from accidental changes, tuple can be used.

Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:

Tuple is immutable so changes cannot be done on the elements of a tuple once it is
assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.

Tuple Assignment:

Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.

Multiple assignment works by creating a tuple of expressions from the right hand
side, and a tuple of targets from the left, and then matching each expression to a
target.

Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:

It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

Tuple as return value:



A Tuple is a comma separated sequence of items.

It is created with or without ( ).
❖ A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tuple as argument:

The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
Sets

What is a Set?

• A set is a well-defined collection of distinct objects.


– Example: A = {1, 2, 3, 4, 5}

What is an element of a Set?

• The objects in a set are called its elements.


– So in case of the above Set A, the elements would be 1, 2, 3, 4, and
5. We can say,1  A, 2  A etc.

• Usually we denote Sets by CAPITAL LETTERs like A, B, C, etc. while


their elementsare denoted in small letters like x, y, z etc.

• If x is an element of A, then we say x belongs to A and we represent it


as x  A

• If x is not an element of A, then we say that x does not belong to A and


we represent it as
xA

How to describe a Set?

• Roaster Method or Tabular Form

– In this form, we just list the elements

– Example A = {1, 2, 3, 4} or B = {a, b, c, d, e}

• Set- Builder Form or Rule Method or Description Method

– In this method, we list the properties satisfied by all elements


of the set

– Example A = {x : x  N, x < 5}
Some examples of Roster Form vs Set-builder Form
Roster Form Set-builder Form
1 {1, 2, 3, 4, 5} {x | x  N, x <6}

2 {2, 4, 6, 8, 10} {x | x = 2n, n  N, 1 ≤ n ≤ 5}

3 {1, 4, 9, 16, 25, 36} {x | x = n2, n  N, 1 ≤ n ≤ 6}

Sets of Numbers
1. Natural Numbers (N)

• N = {1, 2, 3,4 ,5 6, 7, …}

2. Integers (Z)

• Z = {…, -3, -2, -1, 0, 1, 2, 3, 4, …}

3. Whole Numbers (W)

• W = {0, 1, 2, 3, 4, 5, 6…}

4. Rational Numbers (Q)

• {𝑝 : p  Z, q  Z, q ≠ 0}
𝑞

Finite Sets & Infinite Sets

• Finite Set: A set where the process of counting the


elements of the set wouldsurely come to an end is called
finite set
• Example: All natural numbers less than 50
• All factors of the number 36
• Infinite Set: A set that consists of uncountable number of
distinct elements iscalled infinite set.
• Example: Set containing all natural numbers {x |
x  N, x > 100}

Cardinal number of Finite Set

• The number of distinct elements contained in a finite set A


is called the cardinalnumber of A and is denoted by n(A)

• Example A = {1, 2, 3, 4} then n(A) = 4

• A = {x | x is a letter in the word ‘APPLE’}. Therefore A =


{A, P, L, E} and
n(A) = 4

• A = {x | x is the factor of 36}, Therefore A = { 1, 2, 3, 4,


6, 9, 12, 18, 36}and n(A) = 9

Empty Set

• A set containing no elements at all is called an empty set or a


null set or a void set.

• It is denoted by ϕ (phai)

• In roster form you write ϕ = { }

• Also n (ϕ) = 0

• Examples: {x | x  N, 3 < x <4} = ϕ

• {x | x is an even prime number, x > 5} = ϕ

Non Empty Set

• A set which has at least one element is called a non-empty set

• Example: A = {1, 2, 3} or B = {1}


Singleton Set

• A set containing exactly one element is called a singleton set

• Example: A = {a} or B = {1}

Equal Sets

• Two set A and B are said to be equal sets and written as A = B


if every element ofA is in B and every element of B is in A

• Example A = {1, 2, 3, 4} and B = {4, 2, 3, 1}

• It is not about the number of elements. It is the elements


themselves.

• If the sets are not equal, then we write as A ≠ B


Equivalent Sets

• Two finite sets A and B are said to be equivalent,


written as A ↔ B,if n(A) = n(B), that is they have
the same number of elements.

• Example: A = {a, e, i, o, u} and B = {1, 2, 3, 4, 5},


Therefore n(A) = 5 andn(B) = 5 therefore A ↔ B

• Note: Two equal sets are always equivalent but two


equivalent sets need not beequal.
Subsets

• If A and B are two sets given in such a way that every


element of A is in B, thenwe say A is a subset of B and we
write it as A ⊆ B

• Therefore is A ⊆ B and x  A then x  B

• If A is a subset of B, we say B is a superset of A and is written as


BA
• Every set is a subset of itself.

• i.e. A ⊆ A, B ⊆ B etc.

• Empty set is a subset of every set

• i.e. ϕ ⊆ A, ϕ ⊆ B

• If A ⊆ B and B ⊆ A, then A = B
• Similarly, if A = B, then A ⊆ B and B ⊆ A

• If set A contains n elements, then there are 2n subsets of A


Power Set

• The set of all possible subsets of a set A is called the power set of A,
denoted by P(A). IfA contains n elements, then P(A) = 2n sets.

• i.e. if A = {1, 2}, then P(A) = 22 = 4

• Empty set is a subset of every set

• So in this case the subsets are {1}, {2}, {2, 3} & ϕ


Proper Subset

• Let A be any set and let B be any non-empty subset. Then A is called
a proper subset ofB, and is written as A  B, if and only if every
element of A is in B, and there exists at least one element in B
which is not there in A.

– i.e. if A ⊆ B and A  B, then A  B

– Please note that ϕ has no proper subset

– A set containing n elements has (2n – 1) proper subsets.

• i.e. if A = {1, 2, 3, 4}, then the number of proper subsets is


(24 – 1) = 15
Universal Set

• If there are some sets in consideration, then there happens to be a


set which is a supersetof each one of the given sets. Such a set is
known as universal set, to be denoted by U or


• i.e. if A = {1, 2}, B = {3, 4}, and C = {1, 5}, then U or  = {1,
2, 3, 4, 5}

Operations on Sets

• Union of Sets

• The union of sets A and B, denoted by A  B, is the set of all


those elements, eachone of which is either in A or in B or in
both A and B

• If there is a set A = {2, 3} and B = {a, b}, then A  B = {2, 3, a,


b}

• So if A  B = {x | x  A or x  B}

• , then x  A  B which means x  A or x  B

• And if x  A  B which means x  A or x  B


• Interaction of Sets

• The intersection of sets A and B is denoted by A  B, and is a


set of all elementsthat are common in sets A and B.

• i.e. if A = {1, 2, 3} and B = {2, 4, 5}, then A  B = {2} as 2 is the


only commonelement.

• Thus A  B = {x: x  A and x  B} then x  A  B i.e. x  A and x


B

• And if x  A  B i.e. x  A and x  B

• Disjointed Sets

• Two sets A and B are called disjointed, if they have no


element in common.Therefore:

• A  B = ϕ i.e. if A = {2, 3} and B = {4, 5}, then A  B = ϕ

• Intersecting sets
• Two sets are said to be intersecting or overlapping or
joint sets, if they haveat least one element in common.

• Therefore two sets A and B are overlapping if and only if


ABϕ

• Intersection of sets is Commutative

i.e. A  B = B  A for any sets A and B

• Intersection of sets is
Associative

• i.e. for any sets, A, B, C,

• (A  B)  C = A  (B  C)

• If A ⊆ B, then A  B = A

• Since A ⊆ , so A   = A

• For any sets A and B, we have

• A  B ⊆ A and A  B ⊆ B

• A  ϕ = ϕ for every set A

• Difference of Sets

• For any two sets A and B, the difference A – B is a set of all


those elements of Awhich are not in B.
i.e. if A = {1, 2, 3, 4, 5} and B = {4, 5, 6}, Then A – B = {1, 2, 3} and B – A =
{6}

Therefore A – B = {x | x  A and x  B}, then x  A – B then x  A but x 


B

• If A  B then A – B = 
• Complement of a Set

• Let x be the universal set and let A  x. Then the complement


of A, denoted by A’is the set of all those elements of x which
are not in A.

• i.e. let  = {1, 2, 3, 4, 5,6 ,7 ,8} and A = {2, 3,4 }, then A’ =


{1, 5, 6, 7, 8}

• Thus A’ = {x | x   and x  A} clearly x  A’ and x  A

• Please note

• ’ =  and ’= 

A  A’ =  and A  A’ = ϕ

Disruptive laws for Union and Intersection of Sets

• For any three sets A, B, C, we have the following

• A  (B  C) = (A  B)  (A  C)
Say A = {1, 2}, B = {2, 3} and C = {3, 4}

Therefore A  (B  C) = {1, 2, 3} and

And (A  B)  (A  C) = {1, 2, 3} and hence equal

• A  (B  C) = (A  B)  (A  C)
Say A = {1, 2}, B = {2, 3} and C = {3, 4}

Then A  (B  C) = {2} and (A  B)  (A  C) = {2} and


hence equal

Disruptive laws for Union and Intersection of Sets

• De-Morgan’s Laws

– Let A and B be two subsets of a universal set , then


• (A  B)’ = A’  B’

• (A  B)’ = A’  B’

Let  = {1, 2, 3, 4, 5, 6} and A = {1, 2, 3} and B = {3, 4, 5}

Then A  B = {1, 2, 3, 4, 5}, therefore (A  B)’ = {6}

A’ = {4, 5, 6} and B’ = {1, 2, 6}

Therefore A’  B’ = {6}. Hence proven

Python Set Methods

A Set in Python is a collection of unique elements which are unordered and mutable.
Python provides various functions to work with Set. In this article, we will see a list of
all the functions provided by Python to deal with Sets.

Functions Name Description


add() Adds a given element to a set
clear() Removes all elements from the set
copy() Returns a shallow copy of the set
difference() Returns a set that is the difference
between two sets
difference_update() Updates the existing caller set with the
difference between two sets
discard() Removes the element from the set
intersection() Returns a set that has the intersection of
all sets
intersection_update() Updates the existing caller set with the
intersection of sets
pop() Returns and removes a random element
from the set
remove() Removes the element from the set
union() Returns a set that has the union of all sets
update() Adds elements to the set
Dictionaries:


Dictionary is an unordered collection of elements. An element in
dictionary has a key: value pair.

All elements in dictionary are placed inside the curly braces i.e. { }

Elements in Dictionaries are accessed via keys and not by their position.

The values of a dictionary can be any data type.

Keys must be immutable data type (numbers, strings, tuple)

Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership

Operations Example Description

Creating a >>> a={1:"one",2:"two"} Creating the dictionary with


dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
accessing an >>> a[1] Accessing the elements by using
element 'one' keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False
Methods in dictionary:

Method Example Description

a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
a.items() >>> a.items() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), (3, the dictionary's items. It
'three')]) displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
a.pop(key) >>> a.pop(3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.

setdefault(key,value) >>> a.setdefault(3,"three") If key is in the


'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> a.setdefault(2) a value of dictionary and
'two' return dictionary.
a.update(dictionary) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
with the existing
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} dictionary
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
len(a) >>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])

Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
❖ ❖ ❖
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical

doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
❖ ❖
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.

Dictionary is used
when data is being
constantly modified.

PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Difference between del and remove methods in List?
5. Difference between pop and remove in list?
6. How are the values in a tuple accessed?
7. What is a Dictionary in Python
8. Define list comprehension
9. Write a python program using list looping
10. Define Tuple and show it is immutable with an example.
11. state the difference between aliasing and cloning in list
12. what is list cloning
13. what is deep cloning
14. state the difference between pop and remove method in list
15. create tuple with single element
16. swap two numbers without using third variable
17. define properties of key in dictionary
18. how can you access elements from the dictionary
19. difference between delete and clear method in dictionary
20. What is squeezing in list? give an example
21. How to convert a tuple into list
22. How to convert a list into tuple
23. How can you return multiple values from function?
24. Find length of sequence without using library function.
25. how to pass tuple as argument
26. how to pass a list as argument
27. how can you insert values into dictionary
28. what is key value pair
29. mention different data types can be used in key and value
30. What is the use of from keys() in dictioanary.

PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix addition
8. write a program for matrix subtraction
9. Explain in detail about dictionaries and its methods.
10. Explain in detail about advanced list processing.

You might also like