Unit 3 PPTs
Unit 3 PPTs
• In python, A list is sequence of values called items or elements. The elements can be any type..
• A sequence is an object that holds multiple items of data, stored one after
the other.
• So A list is a sequence object that contains multiple data items.
• We use square bracket[ ] to represent a list.
Properties:
1. Lists are mutable, which means that their contents can be changed
during a program’s execution
2. Lists are dynamic data structures, meaning that items may be added to
them or removed from them
3. You can use indexing, slicing, and various methods to work with lists in a program.
Creating List
• A list Class defines lists. A programmer can use a list’s
Constructor to create list or [] syntax.
a. Create a empty list L1=list(); or L1=[]
b. Create a list with any three integer elements L2= list([10,20,30]) or L2= [10,20,30]
L5= list(“xyz”)
Python - 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.
• Good thing about a list that items in a list need not all have the same type:
• Creating a list is as simple as putting different comma-separated values of
different types. For example:
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists:
• To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
This will produce following result: list1[0]: physics list2[1:5]: [2, 3, 4, 5]
The negative Index access the elements from the end of a list counting in backward direction. The
index of the last element of any non empty list is always -1.
>>>list1=[10,20,30,40,50,60]
>>>list1[-1] will give 60
>>>list1[-2] will give 50
>>>list1[-3] will give 40
>>> list1[-6] will give 10
A Quick Question?
OUTPUT: [1,3,5,7,9]
List Slicing
Slicing examples
• If numbers = [1, 2, 3, 4, 5]
• 2>>> print(numbers) [1, 2, 3, 4, 5]
• >>> print(numbers[2:]) [3, 4, 5]
• >>> print(numbers[:]) [1, 2, 3, 4, 5]
• If numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• >>> print(numbers[1:8:2]) [2, 4, 6, 8]
• >>> print(numbers[-5:])[6, 7, 8, 9, 10]
Slicing:
• Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']
FindList=[10,20,30,40,50]
print(FindList[:3])
print(FindList[::-1])
print(FindList[-1:0:-1])
OUTPUT—
[10, 20, 30]
The * symbol multiplies two numbers. However, when the operand on the left side of the * symbol is a
sequence (such as a list) and the operand on the right side is an integer, it becomes the repetition
operator.
output: [InfyTqInfyTqInfyTq]
• To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know. Remove method will ask
for value to be deleted.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
del list1[2];
print ("After deleting index 2 : “)
print (list1)
• This will produce following result:
After deleting value at index 2 :
['physics', 'chemistry', 2000]
>>>list1.remove('physics')
>>> list1 ['chemistry', 2000]
Del Examples
• >>> MyList=[10,20,30,40,50,60]
• >>> MyList
• [10, 20, 30, 40, 50, 60]
• >>> del MyList[1]
• >>> MyList
• [10, 30, 40, 50, 60]
• >>> del MyList[-1]
• >>> MyList
• [10, 30, 40, 50]
• >>> del MyList[1:3]
• >>> MyList
• [10, 50]
Finding length of List
• Python has a built-in function named len that returns the length of a sequence, such as a
list. The following code demonstrates:
my_list = [10, 20, 30, 40] size = len(my_list) print(size) will give 4
• The first statement assigns the list [10, 20, 30, 40] to the my_list variable.
• The second statement calls the len function, passing the my_list variable as an argument
CONCATENATION
• >>>a=[2, 56]
• >>> b=["anj","d"]
• >>> a+b
• [2, 56, 'anj', 'd']
Membership test
• in operations can be applied to test the whether an element is part of list or not.
• 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
([1, 2, 3]) Length
• A=[]
• For i in range(5):
A[i]= int(Input(“Enter the sale”))
2. Write a python program to read sales of five days in list using loop
• sales[index] = float(input())
• index += 1
• print(value)
Expected output
Checkpoint Question
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
numbers2 += numbers1
print(numbers1)
print(numbers2)
OUTPUT:[1,2,3]
[10,20,30,1,2,3]
a=['a','b','c']
a+="hello"
print(a) ['a', 'b', 'c', 'h', 'e', 'l', 'l', 'o']
b=a+"hello"
print(b) ERROR!
Traceback (most recent call last):
File "<main.py>", line 12, in <module>
TypeError: can only concatenate list (not "str") to list
Copying list
Recall that in Python, assigning one variable to another variable simply makes both variables reference
the same object in memory.
• For example, look at the following code:
• list1 = [1, 2, 3, 4]
• list2 = list1
• After this code executes, both variables list1 and list2 will reference the same list in memory.
Copied Lists refers to same object
• To demonstrate this,
• >>> list1 = [1, 2, 3, 4]
• >>> list2 = list1
• >>> print(list1)
• [1, 2, 3, 4]
• >>> print(list2)
• [1, 2, 3, 4]
• >>> list1[0] = 99
• >>> print(list1)
• [99, 2, 3, 4]
• >>> print(list2)
• ?????????
Creating different but identical lists
• Suppose you wish to make a copy of the list, so that list1 and list2 reference two separate but
identical lists.
• One way to do this is with a loop that copies each element of the list. Here is an example:
• # Create a list with values.
• list1 = [1, 2, 3, 4]
• # Create an empty list.
• list2 = []
• # Copy the elements of list1 to list2.
• for item in list1:
• list2.append(item) OR we can use :
• list1 = [1, 2, 3, 4]
• list2 = [] + list1
Using built in methods
List1=[“red”,”blue”,”pink”]
• List2=List1.copy() # will copy list1 to list2
>>>list2 will give [“red”,”blue”,”pink”]
Or we can use List2=list1[:]
LISTS
Examples
MyList=[10,20,30,40,50]
print(MyList) print(len(MyList)) print(max(MyList)) print(min(MyList)) print(sum(MyList))
import random
random.shuffle(MyList) # will the shuffle in the original list
print(MyList) OUTPUT—
[10, 20, 30, 40, 50]
5
50
10
150
[40, 30, 20, 50, 10]
OUTPUT— [0, 1, 2, 3, 4]
[1, 4, 3, 2, 0]
List Methods in python
Lists have numerous methods that allow you to work with the elements that they contain. Python
provides built-in functions that are useful for working with lists.
List.append()
This method adds an item to the end of the list. MyList = ["apple", "banana", "cherry"]
MyList.append("orange")
print(MyList)
OUTPUT—
['apple', 'banana', 'cherry', 'orange']
Example : Append()
insert( ) method
• This method adds an item Before the specified index of the list. The insert method allows you to
insert an item into a list at a specific position.
• You pass two arguments to the insert method: an index specifying where the item should be
inserted and the item that you want to insert
OUTPUT—
['apple', 'banana', 'orange', 'cherry']
• print(list1)
• list1.remove(item)
• print(list1)
Here are the items in the food list:
• ['P', 'B', 'C']
• ['P', 'C']
pop( ) method #with or without parameter
extend( ) method
This method adds one list at the end of another list. list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2) print(list1)
MyList = ['A','B','C','A','B','C']
print(MyList.count('A'))
OUTPUT— 2
Index method
• Earlier you saw how the ‘in operator’ can be used to determine whether an item is in a list.
• Sometimes you need to know not only whether an item is in a list, but where it is located. The
index method is useful in these cases. You pass an argument to the index method and
• it returns the index of the first element in the list containing that item. If the item is not found in
the list, the method raises a Value Error exception.
Example program: index
reverse( ) method
MyList.reverse( ) print(MyList)
The sort method rearranges the elements of a list so they appear in ascending order (from the lowest
value to the highest value).
>>>my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
>>>my_list.sort()
>>>print('Sorted order:', my_list) Output:
Sorting in reverse
But if we want to sort the elements of the list into descending order, then we must mention
x. sort(reverse=True) Example—
MyList = ['D','B','A','F','E','C']
MyList.sort(reverse=True) print(MyList)
Output—Python
['P', 'y', 't', 'h', 'o', 'n']
Here the list( ) function breaks a string into individual letters.
Question
• Consider the list. Write a Python program to retrieve only the first letter of each word from the
given list.
• words=['Apple','Banana','Orange','Cherry']
Solution
• words=['Apple','Banana','Orange','Cherry']
• MyList=[ ]
• for w in words:
• MyList.append(w[0])
• print(MyList)
•
• OUTPUT—['A', 'B', 'O', 'C']
Checkpoint questions
names = []
Which of the following statements would you use to add the string ‘python’ to the list at
index 0? Why would you select this statement instead of the other?
a. names[0] = ‘python'
b. names.append(‘python')
Write a python function which accepts a list as an argument and returns the sum of the list’s
elements.
• def get_total(value_list):
• total = 0
• for num in value_list:
• total += num
• return total
my_list=[‘two’,5,[‘one’,2]]
print(len(my_list) 3
Mix_list=[‘pet’,’dog’,5,’cat’, ’good’,’dog’]
Mix_list.count(‘dog’) 2
mylist=[‘red’,3]
mylist.extend(‘green’)
Print(len(mylist))
3
Some List Based Questions for Practice
• Using the list L, what is the value of each of the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• Using the list L, what is the value of each of the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• >>> L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
• >>> len(L)
• 5
• >>> len(L[1])
• 9
• >>> L[2]Toyota
• SyntaxError: invalid syntax
• >>> L[4] + '***'
• 'Tesla***'
• >>> L[1] == L[2]
• False
• >>>
Question
• Using the list defined below, what does Python print when these statements are executed?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
(a)for x in L:
print('Item:', x)
(b) size = len(L)
for i in range(size):
print(i+1, L[i])
print("Total count:", size)
• Item: Ford
• Item: Chevrolet
• Item: Toyota
• Item: Nissan
• Item: Tesla
• 1 Ford
• Total count: 5
• 2 Chevrolet
• Total count: 5
• 3 Toyota
• Total count: 5
• 4 Nissan
• Total count: 5
• 5 Tesla
• Total count: 5
def linear_search(My_list,key):
for i in range(len(My_list)):
if My_list[i]==key:
return i
return -1
My_list=[1,5,6,10,15,45,67]
result=linear_search(My_list,32)
if(result!=-1):
print("Element found at position",result)
else:
print("Element not found")
stack = []
print('Initial stack')
print(stack)
# pop() fucntion to pop # element
from stack in # LIFO order
print('\nElements poped from
stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
if My_list[mid]==key:
return mid
elif key>My_list[mid]:
low=mid+1
else:
high=mid-1
return -1
My_list=[10,20,56,516,3576,34324,3245213]
result=binary_search(My_list,34324)
if(result!=-1):
print("Element found at position",result)
else:
print("Element not found")
List Comprehensions
List comprehensions represent creation of new lists from an iterable object(such as list, set, tuple,
dictionary) that satisfy a given condition.
List comprehension contains very less code usually one line to perform a task.
Squares=[]
for i in range(1,101): squares.append(i**2)
OR
Squares=[i**2 for i in range(1,101)] Print(square)
……………………………………………………………
• Q1. Create a list having numbers [1,4,7,10,.....100] as its elements using list comprehension
method.
• Q2. WAP to generate a list of 10 starting multiple of 5 using list comprehension method
Q3. Write list comprehension to generate [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] this list
• 1
mylist = [x+3 for x in range(-2,98,3)]
print(mylist)
Or b=[3*i-2 for i in range(1,35)]
• 2
mylist = [x*5 for x in range (1, 11)] print(mylist)
• 3
num_list = [x for x in range(100) if x % 10 == 0]
print(num_list)
• OR a=[i*10 for i in range(0,10)]
Other Examples
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
CREATING TUPLES
Examples
• Note:
• >>> T1=()
• >>> type(T1)
• <class 'tuple'>
• >>> T2=(10,)
• >>> type(T2)
• <class 'tuple'>
• >>> T3=(10)
• >>> type(T3)
• <class 'int'>
• >>> T4=10,20,30,40
• >>> type(T4)
• <class 'tuple'>
•
• So a single value in parenthesis is not a tuple.
Changing a Tuple
Tup1=tuple("PYTHON")
print(Tup1)
OUTPUT—
('P', 'Y', 'T', 'H', 'O', 'N')
Example—
Tup2=tuple([1,2,3]) print(Tup2)
OUTPUT— (1, 2, 3)
1. len( )
2. max( )
3. min( )
4. sum( )
5. index( )
6. count( )
Example—
codes Output
Tup1=(1,2,3,3,4,5,2) OUTPUT—
1. print(Tup1) 1. (1, 2, 3, 3, 4, 5, 2)
2. 7
2. print(len(Tup1)) 3. 5
3. print(max(Tup1)) 4. 1
5. 1
4. print(min(Tup1))
6.2
5. print(Tup1.index(2))
6. print(Tup1.count(3))
Tuple Examples
Tup2=tuple("CORE PYTHON")
OUTPUT—
1. print(Tup2)
1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')
2. print(len(Tup2))
2. 11
3. print(max(Tup2))
3. Y
4. print(min(Tup2))
4.
5. print(Tup2.index('H')) 5. 8
6. 2
6. print(Tup2.count('O'))
INDEXING & SLICING IN TUPLE
1. print(Tup2) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')
2. print(Tup2[0]) 2. C
3. print(Tup2[5]) 3. P
4. print(Tup2[-5]) 4. Y
5. print(Tup2[-7]) 5.
6. print(Tup2[-1]) 6. N
Example—
1. print(Tup) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')
4. print(Tup[0:]) 4. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')
5. print(Tup[-1::-1]) 5. ('N', 'O', 'H', 'T', 'Y', 'P', ' ', 'E', 'R', 'O', 'C')
OPERATORS IN TUPLE
• + Operator
• * Operator
The + Operator
It is the concatenation operator that is used to join two tuples.
Example—
Tup1=(1,2,3)
Tup2=(4,5,6)
Tup3=Tup1 + Tup2 print(Tup3)
OUTPUT—
(1, 2, 3, 4, 5, 6)
The * Operator
• It is the repetition operator that is used to repeat or replicate the items of a tuple.
Example— Tup=(1,2,3)
Tup2=Tup * 2
print(Tup2) OUTPUT—
(1, 2, 3, 1, 2, 3)
Method1—
Convert given tuple to list and then apply sort( ) method.
Example—
Tup=(1,4,2,5,3)
print(Tup)
List1=list(Tup)
List1.sort()
Tup1=tuple(List1)
print(Tup1)
OUTPUT— (1, 4, 2, 5, 3)
(1, 2, 3, 4, 5)
Method2—
Example:
Tup=(1,4,2,5,3)
print(sorted(Tup))
OUTPUT—
[1, 2, 3, 4, 5]
Sorting Examples
OUTPUT—
['H', 'N', 'O', 'P', 'T', 'Y']
OUTPUT—
['Y', 'T', 'P', 'O', 'N', 'H']
Deleting a Tuple
• We cannot change the items in a tuple. Also we cannot delete or remove items from a tuple.
• But deleting a tuple entirely is possible using the keyword del.
• Example—
Tup_new = ('p','y','t','h','o','n')
print(Tup_new) #('p', 'y', 't', 'h', 'o', 'n')
Tup_new = ('p','y','t','h','o','n')
1. print(Tup_new)
2. print('p' in Tup_new)
3. print('e' in Tup_new)
OUTPUT—
2. True
3. False
4. False
Tuples are more efficient
• Since Python does not have to build tuple structures to be modifiable, they are simpler and more
efficient in terms of memory use and performance than lists
• So in our program when we are making “temporary variables” we prefer tuples over lists
• import sys
• List1=[1,2,3,4]
• Tuple1=(1,2,3,4)
print(green)
print(yellow)
print(red)
• Note: The number of variables must match the
number of values in the tuple, if not, you must use an
asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name
and the
values will be assigned to the variable as a list:
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
print(green)
print(yellow)
print(red)
If the asterisk is added to another variable name than the last, Python will assign values to the
variable until the
number of values left matches the number of variables left.
Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
print(green)
print(tropic)
print(red)
Updating Tuples:
• Tuples are immutable which means you cannot update them or change values of tuple elements.
But we able able to take portions of an existing tuples to create a new tuples as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz'); tup3 = tup1 + tup2; print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')
• 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 :
Tuple vs List
Dictionaries in Python
• A dictionary represents a group of items/elements arranged in the form of key : value pair.
• In Dictionary, the first element is the key and second element is the value associated with the
corresponding key.
• All the elements are enclosed within the curly braces{ }.
• Example—
Dict = {1: ‘python', 2: ‘Program', 3: ‘example'} print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary with Mixed keys Dict = {'Name': ‘Python', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
dict( ) function to create a dictionary in Python
• Dictionary can also be created with the help of the built-in function dict( ). An empty
dictionary can also be created by using curly braces{ }.
• Dict = {}
print("This is an empty Dictionary: ")
print(Dict)
Accessing Values in Dictionary:
• To access dictionary elements, you use the familiar square brackets along with the key to obtain
its value:
• Example:
• If we attempt to access a data item with a key which is not part of the dictionary, we get an error
as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
• This will produce following result:
dict['Zara']:
Traceback (most recent call last): File "test.py", line 4, in
<module> print "dict['Alice']: ", dict['Alice']; KeyError: 'Alice'
Updating Dictionary:
• You can update a dictionary by adding a new entry or item (i.e., a key- value pair), modifying an
existing entry, or deleting an existing entry as shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry dict['School'] = "DPS
School"; # Add new entry print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
• You can either remove individual dictionary elements or clear the entire contents of a dictionary. You
can also delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key
'Name' d
dict.clear(); # remove all entries in dict del dict ; # delete entire
dictionary
• Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins.
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
• This will produce following result:
dict['Name']: Manni
• (b) Keys must be immutable. Which means you can use strings, numbers, or tuples as
dictionary keys but something like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
• This will produce following result. Note an exception raised:
Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']: 'Zara',
'Age': 7};
TypeError: list objects are unhashable
Built-in General Functions applicable on Dictionary:
Output: {‘key1’:0,’key2’:0,’key3’:0}
dict.clear()
• D.get(k) -> D[k] if k in D, else returns None(By default, else can be sent as parameter while calling
• The update() method updates the dictionary with the elements from the another dictionary object
or from an iterable of key/value pairs.
• The update() method takes either a dictionary or an iterable object of key/value pairs (generally
tuples).
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
OUTPUT:{“brand”:”Ford”,”model”:”Mustang”,”year”:1964,”color”:”White”}
• The set default() method returns the value of a key (if the key is in dictionary). If not, it inserts
key with a value to the dictionary.
x = car.setdefault("model", "Bronco")
print(x)
Set default example
Iteration through dictionary:
>>> Grades={"Tammana":"A","Pranav":"B","Sumit":"C"}
>>> for key in Grades: print(key,":",str(Grades[key]))
Nested Dictionaries
Traversing Nested Dictionaries
Sorting Dictionary
• You can obtain a sorted list of the keys using the sorted() function.
>>>prices = {'Apple': 1.99, 'Banana': 0.99, 'Orange': 1.49, 'Cantaloupe': 3.99, 'Grapes': 0.39}
>>>sorted(prices)
['Apple', 'Banana', 'Cantaloupe', 'Grapes', 'Orange'] Can be applied on tuples as well.
Write a function histogram that takes string as parameter and generates a frequency of character
contained in it.
(Hint: Use Dictionary to store character as key and count as value in dictionary. Initially you can take
empty dictionary)
Solution
S=“AAPPLE”
D=dict()
for C in S:
if C not in D:
D[C]=1
else:
D[C]=D[C]+1
print(D)
output-{‘A’:2,’P’:2,’L’:1,’E’:1}
Write a program to print and store squares of upto n numbers in the dictionary
• {1:1,2:4,3:9…….n:n2}
• def sq_of_numbers(n):
• d=dict()
• for i in range(1,n+1):
• if i not in d:
• d[i]=i*i
• return d
• print("sqaures of numbers:")
• Z=sq_of_numbers(5)
• print(Z)
lt=dict(lt)
print(lt)
lt.clear()
print(lt)
1. print(my_dict.get('c'))
2. print(my_dict.get('d'))
3. print(my_dict.get('d',-1))
OUTPUT—
1. 30
2. None
3. -1
my_dict = {'a': 10, 'b': 20, 'c': 30}
1. print(my_dict.pop('b'))
2. print(my_dict.pop('z'))
3. print(my_dict.pop('z', -1))
4. print(my_dict)
output
1. 20
2. Key Error
3. -1
OUTPUT— 293
SETS IN PYTHON
• A set in Python is an unordered collection of unique elements without duplicate elements in the
set.
• Unlike Tuple, Set is Mutable means that once it created, we can change its contents.
Note: A set cannot have a mutable element, like list, set or dictionary, as its element.
Example—
set1 = {1, 2, 3, 4, 5}
print(set1)
OUTPUT—
{1, 2, 3, 4, 5}
{'Python', (1, 2, 3, 4, 5), 5}
Example
set3 = {1, 2, 3, 4, 5, 3, 2, 5}
print(set3)
Output—
{1, 2, 3, 4, 5}
Example—
OUTPUT—
TypeError: unhashable type: 'list'
Example—
2. print(set5)
OUTPUT—
Example—
My_list=[1,2,3,4,5] print(My_list)
My_set=set(My_list) print(My_set)
OUTPUT—
[1, 2, 3, 4, 5]
{1, 2, 3, 4, 5}
Example—
My_tuple=(1,2,3,4,5) print(My_tuple)
My_set=set(My_tuple) print(My_set)
OUTPUT— (1, 2, 3, 4, 5)
{1, 2, 3, 4, 5}
METHODS IN SETS
• add( )
• remove( )
• clear( )
• issubset( )
• issuperset( )
• union( )
• intersection( )
• difference( )
• symmetric_difference( )
add( element)
Add the element into the set.
Example—
set1={1,2,3,4,5}
print(set1)
set1.add(10) print(set1)
OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 10}
remove(element) / discard(element)
Example—
set2={1,2,3,4,5}
print(set2)
OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 4, 5}
issubset( setName)
True
clear( )
set3={1,2,3,4,5}
print(set3)
set3.clear()
print(set3)
OUTPUT—
{1, 2, 3, 4, 5}
set()
issuperset( setName)
• This method checks if one set is superset of another set or not. It give output in Boolean i,e. True
or False
Example—
1. s1={10,20,30,40}
2. s2={10,20,30,40,50}
3. print(s2.issuperset(s1))
OUTPUT—
True
SET OPERATIONS
• union( )
• intersection( )
• difference( )
• symmetric_difference( )
union( ) method
The union of two sets S1 and S2 is a set of elements that are present in S1 or in S2 or in both S1 and S2.
Syntax is:
1. set1.union(set2) Symbol is:| i.e, vertical bar
OUTPUT—
• {40, 10, 50, 20, 30}
Example—
1. s1={10,20,30}
2. s2={10,20,30,40,50}
3. s3=s1 | s2
4. print(s3)
OUTPUT—
{40, 10, 50, 20, 30}
intersection( ) method
The intersection of two sets S1 and S2 is a set of elements that are present in both S1 and S2.
Syntax is: set1.intersection(set2) Symbol is: &
• Example—
• s1={10,20,30}
• s2={10,20,30,40,50}
• print(s1.intersection(s2))
•
• OUTPUT—
Example
1. s1={10,20,30}
2. s2={10,20,30,40,50}
3. s3=s1 & s2
4. print(s3)
OUTPUT—
• {10, 20, 30}
difference( ) method
Syntax is: set1.difference(set2) Symbol is: -
s1={10,20,30,40,50}
s2={30,40,50,60,70}
print(s1.difference(s2))
OUTPUT—
{10, 20}
s1={10,20,30,40,50}
s2={30,40,50,60,70}
s3=s1 - s2
print(s3)# will remove common element from s1
Symmetric_difference( ) method
• The symmetric difference of two sets S1 and S2 is a set of elements that are present in either in S1
or in S2 but not in both sets.
Syntax is: set1.symmetric_difference(set2) Symbol is:^
Example—
1. s1={10,20,30,40,50}
2. s2={30,40,50,60,70}
3. print(s1.symmetric_difference(s2)) OUTPUT—
{20, 70, 10, 60}
Example using symbol
Example— s1={10,20,30,40,50}
s2={30,40,50,60,70}
s3=s1 ^ s2 print(s3)
OUTPUT—
• >>> a={3,4,5}
• >>> b={3,4,534,4}
• >>> a-b
• {5}
• >>> a
• {3, 4, 5}
• >>> b
• {3, 4, 534}
• >>> a.difference_update(b)
• >>> a
• {5}
• >>> b
• {3, 4, 534}
• >>>
NOTE:
We cannot access items in a set by referring to an index, since sets are unordered the elements has no
index.
But we can check if a specified element is present in a set or not, by using the in keyword.
Example—
Myset = {"dell", "sony", "lenovo", "hp"} print("lenovo" in Myset)
OUTPUT—
True
Example—
Myset = {"dell", "sony", "lenovo", "hp"} Myset.add("samsung")
print(Myset)
OUTPUT—
{'lenovo', 'sony', 'dell', 'hp', 'samsung'}
Example— Update
OUTPUT—
{'apple', 'samsung', 'sony', 'dell', 'hp', 'lenovo'}
Solution
• unique=set(input())
• l=list(unique)
• l.sort()
• d=""
• for i in l:
• d+=i
• print(d+str(len(d)))