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

Data_Structure&STR

Uploaded by

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

Data_Structure&STR

Uploaded by

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

Data Structures or Collections

Q: What is Data Structure?

Data Structure is a method of organizing data in memory, this organization


is done by following some rules and regulations. By following these rules a
given problem can solved easily.

Python provide Collection types and each collection type uses one data
structure to organize data.

Collections are containers, which are used to store objects. Grouping


individual objects into object(collection).

Collections allows to group and refer objects with one name. Collections
efficient because these follows some rules and regulations for storing and
reading objects.

Types of collections

Collections are two types.

1. Sequences
a. List
b. Tuple
c. Range
d. String
e. Bytes
f. Bytesarray
2. Non Sequences
a. Set
b. Frozenset
c. Dict

List

List is a sequence data type.


List is a index based collection.
List is an iterable, all collections are iterables. Which allows to read and
write individual objects.
List is a index based collection, where reading and writing is done using
index.
List is mutable type, after creating list we can add,update or delete.
List allows duplicate objects.
Lists are mutable sequences, typically used to store collections of
homogeneous(Similar type) items but it also allows
heterogeneous(different type) items.

How to create list?

Lists may be constructed in several ways:

 Using a pair of square brackets to denote the empty list: []


 Using square brackets, separating items with commas: [a], [a, b, c]
 Using a list comprehension: [x for x in iterable]
 Using the type constructor: list() or list(iterable)

>>> list1=[]

>>> list1
[]

>>> type(list1)

<class 'list'>

>>> list1=[10,20,30,40,50]

>>> list1

[10, 20, 30, 40, 50]

>>> type(list1)

<class 'list'>

>>> student_info=[101,'naresh','python',4000]

>>> student_info

[101, 'naresh', 'python', 4000]

>>> type(student_info)

<class 'list'>

>>> list3=list()

>>> list3

[]

>>> type(list3)

<class 'list'>

>>> list4=list([10,20,30,40,50])

>>> list4

[10, 20, 30, 40, 50]

>>> list5=list(range(1,11,1))

>>> list5
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>

List is index based collection, where reading and writing is done using
index.

Index is an integer value, which is used to identify each item/element of list.


This index value can be +ve or –ve.

+ve index is used to read items from left to right.

-ve index is used to read items/objects from right to left.


Ex:

list1=[10,20,30,40,50]

print(list1[0])

print(list1[1])

print(list1[2])

print(list1[3])

print(list1[4])

for index in range(0,5): # 0 1 2 3 4

print(list1[index])

for index in range(-1,-6,-1): # -1 -2 -3 -4 -5


print(list1[index])

for index in range(4,-1,-1): # 4 3 2 1 0

print(list1[index])

for index in range(-5,0,1): # -5 -4 -3 -2 -1

print(list1[index])

print("Length of list is ",len(list1))

len() : It is predefined function in python, which is used to find length of list


or return count of items of list.

Syntax: len(collection/iterable)

# write a program to print sum of list

list1=[10,20,30,40,50]

s=0

for index in range(0,len(list1)): # 0 1 2 3 4

s=s+list1[index] # 0+10 ==> 10+20=30+30=60+40=100+50=150

for index in range(0,len(list1)):

print(f'Element at {index} is {list1[index]}')

print(f'Sum is {s}')

Python allows to read items/objects from list in different ways.

1. Index
2. Slicing
3. For loop
4. Iterator
5. Enumerate
Python allows to read items/objects from list in different ways.

1. Index
2. Slicing
3. For loop
4. Iterator
5. Enumerate

Index is used to read and write items of list, it allows to read and write
items sequentially and randomly. Using index we can read or write
only one item.

Example:

list1=[10,20,30,40,50]

print(list1[0])

print(list1[1])

print(list1[4])

print(list1)

list1[1]=100 # updating item of the list

print(list1)

del list1[2]

print(list1)

Slicing is a process of reading a part of sequence (list,string,tuple,…).


Slicing is supported by all index based sequences or collections.
Slicing allows to read and write more than one value. It is done in
two ways.

1. Slice operator
2. Slice object
Slice Operator

Syntax of slice operator is,

Sequence-name[startindex:stopindex:step]

Slice operator uses range for generating indexes.

Startindex,stopindex and step or optionally, default values are


startindex is 0, stopindex is length of sequence and step +1. Step
should not be zero.

Slicing operator return a new list of sequence.

Example:

list1=list(range(10,110,10))

print(list1)

list2=list1[::] # start=0,stop=len(list1),step=+1

list3=list1[:] # start=0,stop=len(list1),step=+1

print(list2)

print(list3)
list4=list1[::-1] # start=-1,stop=-len(list1)+1,step=-1

print(list4) # if step is -ve, the default start=-1 and stop=-len(seq)+1

list5=list1[::-2] # start=-1,stop=-len(list1)+1,step=-2

print(list4)

print(list5)

list6=list1[::2] # start=0,stop=len(list1),step=+2

print(list6)

Example:

list1=list("PROGRAMMING")

print(list1)

list2=list(range(10,110,10))

print(list2)

list3=[10,20,30,40,50]

print(list3)

Example:

list1=list(range(1,11,1))

print(list1)

list2=list1[::2]

list3=list1[::-2]

print(list2)

print(list3)
list4=list1[0:6:2]

list5=list1[-1:-8:-2]

print(list4)

print(list5)

list6=list1[len(list1)-1::-1] # list1[9::-1]

list7=list1[-len(list1)::1] # list1[-10::1]

print(list6)

print(list7)

Note: start<stop if step is +ve, start>stop if step is –ve

Slice object

Slice object is reusable. We create slice object with start, stop and
step. This object can be applied to one or more than one sequence.

Syntax of slice object:

slice(start,stop,[step])
slice(stop)

Exmaple

list1=[10,20,30,40,50,60,70,80,90,100]

list2=[1,2,3,4,5,6,7,8,9,10]

list3=[2,4,6,8,10,12,14,16,18,20]

s=slice(0,5)

list4=list1[s]

list5=list2[s]
list6=list3[s]

print(list1)

print(list2)

print(list3)

print(list4)

print(list5)

print(list6)

Iterator

Iterator is a cursor which is used to read elements or items from


collection or sequence or iterables.

Iterator is read only cursor, it allows to read from underlying


sequence but does not allows modify.

Syntax of creating iterator object

iter(iterable)

This function return iterator object created on iterable.


Iterator

Iterator is a cursor which is used to read elements or items from collection


or sequence or iterables.

Iterator is read only cursor, it allows to read from underlying sequence but
does not allows modify.

Syntax of creating iterator object

iter(iterable)

This function return iterator object created on iterable.

course_list=['java','python','.net','c','c++']
x=iter(course_list)
c1=next(x)
c2=next(x)
c3=next(x)
c4=next(x)
c5=next(x)
print(c1,c2,c3,c4,c5)
c6=next(x) # error

Using iterator object we can iterate on list only one time.

Iterator is given to for loop, so that it can read each time one value.
For loop internally calls next() function of iterator, which return next
value from iterable.

list1=list(range(10,110,10))

print(list1)

e=iter(list1)

e1=next(e)

e2=next(e)

print(e1,e2)

for x in e: # next(e)

print(x)

Enumerate
Enumerate is a cursor which is used to read elements from
iterables(collections). Enumerate return two values 1. Index 2. Value
This is useful in construction of dictionary object.

Syntax:

enumerate(iterable)

enumerate() is a predefined function which return enumerate object of


iterable.

list1=[10,20,30,40,50]
x=enumerate(list1)
e1=next(x)
e2=next(x)
print(e1)
print(e2)
for e in x:
print(e)

for loop

for loop is used to read elements from iterables or sequences. For loop
internally create iterator on iterable and calls next() function.

Syntax:

for variable in iterable(list/set/..):


statement-1
statement-2

for loop each time read one value from iterable and execute statements.
This repeating is done until all the elements read from iterable.

list1=[10,20,30,40,50]
for e in list1:
print(e)
Mutable Operations of List

List is a mutable sequence. After creating list we can add, update and
delete items.

1. append(ele) : This method is used to add element at the end of list.

Example:
list1=[]
list1.append(10)
list1.append(20)
list1.append(30)
list1.append(40)
for value in list1:
print(value)

Exmaple:
# write a program to read scores of n players and display
scores=[]
n=int(input("enter how many players")) # 3
for i in range(n): # 0 1 2
s=int(input("enter score"))
scores.append(s)
for score in scores:
print(score)

Example:
# write a program to read n integers into list
# after reading separate even no into even list
# odd numbers into odd list

numbers=[]
n=int(input("Enter how many numbers"))
for i in range(n):
num=int(input("enter any number"))
numbers.append(num)
enumbers=[]
onumbers=[]

for num in numbers:


if num%2==0:
enumbers.append(num)
else:
onumbers.append(num)

print(numbers)
print(enumbers)
print(onumbers)

Example:
# write a program to read name and n subjects marks
# display total and avg

name=input("enter name")
n=int(input("enter how many subject marks"))
marks=[]
for i in range(n):
s=int(input("enter marks"))
marks.append(s)

total=sum(marks)
avg=total/n

print(name)
print(marks)
print(total)
print(avg)
extends s with the contents of t (for the most part
s.extend(t) or s += t
the same as s[len(s):len(s)] = t)
Example

list1=[10,20,30,40,50]

list2=[60,70,80]

print(list1)

print(list2)

list1.extend(list2)

print(list1)

Example

list1=[1,2,3,4,5]

list2=[6,7,8,9,10]

list1[len(list1):len(list1)]=list2

print(list1)

Example

python_batch1=['suresh','kishore','naresh']

python_batch2=['kiran','ramesh','rajesh','abhishek']

python_batch1.extend(python_batch2)

print(python_batch1)

s.insert(i, inserts x into s at the index given by i (same as s[i:i] =


x) [x])
Example

list1=[10,20,30,40,50]

list1.insert(1,60)

print(list1) # [10,60,20,30,40,50]

list1.insert(0,90)

print(list1)

Example

list1=[100,200,300,400,500]

list2=[600,700,800]

list1[2:2]=list2

print(list1)

Explanation: insert method of list insert only one object at given index.

List-name.insert(index,value)

In order to insert more than one value at given position we use slicing.

List-name[start-index:stop-index]

Starting and stop index must be same.

List1=[100,200,300,400,500]

List1[1:1]=[1000,2000,3000]

s[i] = x item i of s is replaced by x


slice of s from i to j is replaced by the contents of the
s[i:j] = t
iterable
Index is used to perform operation on one element.
Slicing is used to perform operation on group of elements.

Example

list1=[10,20,30,40,50]

print(list1)

list1[1]=60

print(list1)

The value at index 1 is replace with value 60

Example

list1=[10,20,30,40,50]

list1[1:4]=[100,200,300]

print(list1)

Output: [10, 100, 200, 300, 50]

The values from 1 to 4 are replaced with 100,200,300

Slice uses range for generating values. Stop index is not included.
Example

list1=[1,2,3,4,5,6,7,8,9,10]

list2=[10,20,30,40,50]

list1[0::2]=list2

print(list1)

Output: [10, 2, 20, 4, 30, 6, 40, 8, 50, 10]

Example

list1=list(range(10,110,10))

print(list1)

list1[-1::-1]=range(1,11)

print(list1)

Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Deleting Elements from list


1. Deleting element is done using index
2. Deleting multiple elements are done using slicing
3. Deleting element without index is done using remove
4. Deleting all elements are done using clear method

Deleting is done using del keyword.


Remove method of list
Clear method of list

Example

list1=[10,20,30,40,50]

del list1[0]

print(list1)

Output: [20, 30, 40, 50]

On deletion of element, the elements which are at right side shifted towards
left side. In above example 10 element is deleted using index 0. After
deleting 20,30,40,50 are shifted one position left side.
Deleting Elements from list

1. Deleting element is done using index


2. Deleting multiple elements are done using slicing
3. Deleting element without index is done using remove
4. Deleting all elements are done using clear method

Deleting is done using del keyword.


Remove method of list
Clear method of list

Example

list1=[10,20,30,40,50]

del list1[0]

print(list1)

Output: [20, 30, 40, 50]

On deletion of element, the elements which are at right side shifted towards
left side. In above example 10 element is deleted using index 0. After
deleting 20,30,40,50 are shifted one position left side.

Example

list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
del list1[8] # using index we can delete one element
print(list1)
del list1[1:4] # using slicing we can delete more than one element
print(list1)

Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 20, 30, 40, 50, 60, 70, 80, 100]
[10, 50, 60, 70, 80, 100]

Example
list1=list(range(10,110,10))
print(list1)
del list1[1::2] # delete all elements from 1 to till the end of list
# by incrementing index with 2
print(list1)
list2=list(range(1,11))
print(list2)
del list2[-1:-5:-1] # delete all elements from -1 to -4
print(list2)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 30, 50, 70, 90]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6]

Example

Remove Method of list, its remove value/element from list using value but
not using index.

list1=[10,20,30,40,50]
print(list1)
list1.remove(20)
print(list1)
list1.remove(100)

Output:
[10, 20, 30, 40, 50]
[10, 30, 40, 50]
Traceback (most recent call last):

File "C:/Users/admin/Desktop/python7am/p139.py", line 5, in <module>

list1.remove(100)

ValueError: list.remove(x): x not in list


Example

Write a program to read n names and delete a given name

names_list=[]

n=int(input("Enter how many names"))

for i in range(n):

name=input("enter name")

names_list.append(name)

print(names_list)

name=input("enter name to delete")

if name in names_list:

names_list.remove(name)

print("name deleted")

else:

print("name not exists")

print(names_list)

Output:

Enter how many names3

enter namesuresh

enter namerajesh

enter namenaresh

['suresh', 'rajesh', 'naresh']


enter name to deletesuresh

name deleted

['rajesh', 'naresh']

Removing all the elements or values can be done using clear method.

list1=[10,20,30,40,50]
list1.clear()
print(list1)
list2=[10,20,30,40,50]
list2[:]=[] # updating list2 with empty list
print(list2)

Application which perform all list operations.


websites list

***MENU***

1. Add
2. Updating
3. Removing
4. View
5. Exit

Enter your option :

website_list=[]

while True:

print("***MENU****")

print("1. Add")

print("2. Update")

print("3. Remove")

print("4. View")

print("5. Exit")

opt=int(input("enter your option"))

if opt==1:

site_name=input("Enter website name")

website_list.append(site_name)

print("website name added")

elif opt==2:

site_name=input("Enter website name to update")

if site_name in website_list:

i=website_list.index(site_name)

nsite_name=input("Enter new website name")

website_list[i]=nsite_name

print("website name updated")


else:

print("given website is not exists in the list")

elif opt==3:

site_name=input("Enter website name to delete")

if site_name in website_list:

website_list.remove(site_name)

print("website name is removed from list")

else:

print("given website name not exists in the list")

elif opt==4:

for name in website_list:

print(name)

elif opt==5:

break

else:

print("invalid option")
Using list as Stack

Stack is data structure which follows LIFO (Last In First Output) approach.
The element which is inserted last is removed first.
In python stack can be implemented using List.

Stack allows two operations.

1. Push : adding element into stack


2. Pop : removing and reading element from stack

append() : This method is used to push element into stack


pop() : This method is used to read and remove element from stack

Stack Operations
1. Push
2. Pop
3. Exit
Enter your option
stack=[]
while True:
print("***Stack Operations***")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option"))
if opt==1:
ele=int(input("enter element"))
stack.append(ele)
print("element pushed inside stack")
elif opt==2:
if len(stack)==0:
print("stack is empty")
else:
ele=stack.pop()
print(ele,"is poped from stack")
elif opt==3:
print(stack)
elif opt==4:
break

Using list as Queue


Queue is a data structure which follows FIFO (First In First Out), the
element inserted first is remove first. The elements are inserted at rear end
and removing is done from front end.

Adding element is done using append method.


Removing element is done using del keyword.

Queue Operations
1. Adding Element
2. Removing Element
3. Display Queue
4. Exit
Enter Your option

queue=[]
while True:
print("Queue Operations")
print("1. Adding Element")
print("2. Removing Element")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option"))
if opt==1:
ele=int(input("enter element"))
queue.append(ele)
print("element is added into queue")
elif opt==2:
if len(queue)==0:
print("Queue is empty")
else:
ele=queue[0]
del queue[0]
print(ele,"is removed from queue")
elif opt==3:
print(queue)
elif opt==4:
break

s.copy() creates a shallow copy of s

Types of copy
1. Shallow Copy
2. Deep Copy
Shallow Copy : Shallow copy is reference copy. It will copy addresses of
objects from one sequence(list) to another sequence(list).

Deep Copy : deep copy is object copy, it will create copy of object and
store into another sequence or list. In order to perform deep copy import
one module called copy. This module is having deepcopy function, this will
create deepcopy of sequence or list.

Import copy
Example of shallow copy

list1=[10,20,30,40,50]
list2=list1.copy() # shallow copy
print(list1)
print(list2)
list3=[[10,20]]
list4=list3.copy()
print(list3)
print(list4)
list3[0].append(30)
print(list3)
print(list4)

Example of Deep Copy

import copy
list1=[[10,20]]
list2=copy.deepcopy(list1)
print(list1)
print(list2)
list1[0].append(30)
print(list1)
print(list2)

Nested List
List within list is called nested list. Nested list can be used as matrices.
In Nested list data is organized in multiple rows and columns.

Nested list elements are identified with row index and column index. This
index can be +ve or –ve

# creating nested list and displaying


list1=[[10,20],[30,40],[50,60]]
print(list1)
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[0][0],list1[0][1])
print(list1[1][0],list1[1][1])
print(list1[2][0],list1[2][1])
# reading using for loop with index
for i in range(3): # 0 1 2
for j in range(2): # 0 1
print(list1[i][j],end=' ')
print()

# reading using for loop without using index


for x in list1:
for v in x:
print(col,end=' ')
print()

print(list1[-1][-1],list1[-1][-2])
print(list1[-2][-1],list1[-2][-2])
print(list1[-3][-1],list1[-3][-2])

# write a program to read 2x2 matrix and display


matrix=[[],[]]
for i in range(2): # 0 1
for j in range(2): # 0 1
ele=int(input("enter any element"))
matrix[i].append(ele)
print(matrix)
for row in matrix:
for col in row:
print(col,end=' ')
print()

# write a program to read MxN matrix and display

m = int(input('enter no of rows'))n = int(input('Enter no of colums'))matrix=


[]for i in range(m): matrix.append([]) for j in range(n):
matrix[i].append(int(input('Enter Value')))
print(matrix)
# write a program to M clases N Students and display
# The number of students in each class is not same.

students=[]
m=int(input("enter how many classes")) #5
for i in range(m):
students.append([])
n=int(input("enter how many students"))
for j in range(n):
name=input("enter name")
students[i].append(name)

for row in students:


for col in row:
print(col,end=' ')
print()

# Write a program to add two matrices

m=int(input("enter how many rows"))


n=int(input("enter how many cols"))
matrix1=[]
matrix2=[]
matrix3=[]
print("Enter the elements of matrix1")
for i in range(m):
matrix1.append([])
for j in range(n):
ele=int(input("Eneter element"))
matrix1[i].append(ele)

print("Enter the elements of matrix2")


for i in range(m):
matrix2.append([])
for j in range(n):
ele=int(input("Enter element"))
matrix2[i].append(ele)

for i in range(m):
matrix3.append([])
for j in range(n):
matrix3[i].append(matrix1[i][j]+matrix2[i][j])

print(matrix1)
print(matrix2)
print(matrix3)

List Comprehension

For constructing a list, a set or a dictionary Python provides special syntax


called “displays”, each of them in two flavors:

 either the container contents are listed explicitly, or


 they are computed via a set of looping and filtering instructions, called
a comprehension

1st approach
list1=[10,20,30,40,50,60]
list2=[10+20,1+2,3+4,5+6]

2nd approach: List comprehension

Syntax-1: list-name=[expression for variable in iterable]


Syntax-2: list-name=[expression for variable in iterable if test]
Syntax-3: list-name=[expression for variable in iterable for variable in
iterable]
Syntax-4:list-name=[expression for variable in iterable for variable in ietable
if test]

Syntax1:

Example
names_list=['naresh','suresh','kishore','rajesh','ramesh']
names_list1=[name.upper() for name in names_list]
names_list2=[name.title() for name in names_list]
names_list3=[name.lower() for name in names_list]

# without comprehension
list1=[]
for name in names_list:
list1.append(name.upper())

print(names_list)
print(names_list1)
print(names_list2)
print(names_list3)

Example
list1=list(range(1,11))
print(list1)
list2=[chr(n) for n in range(65,91)]
list3=[chr(n) for n in range(97,123)]
print(list1)
print(list2)
print(list3)

list4=[]
for n in range(65,91):
list3.append(chr(n))
print(list4)
Syntax-2: list-name=[expression for variable in iterable if test]
1. For loop read each time one value from iterable.
2. After reading value test condition, if condition is True
3. Eval expression and result is stored into the list

This syntax is called filter.

Example

sales_list=[15000,20000,12000,14000,25000,11000]
sales_list1=[sale for sale in sales_list if sale>=15000]
sales_list2=[sale for sale in sales_list if sale<15000]
print(sales_list)
print(sales_list1)
print(sales_list2)

Example
numbers_list=[1,2,3,5,7,8,11,12,13,14,27,29,25,23]
numbers_list1=[num for num in numbers_list if num%2==0]
numbers_list2=[num for num in numbers_list if num%2!=0]
print(numbers_list)
print(numbers_list1)
print(numbers_list2)

Example:

list_str=['abc','XYZ','pqr','MNO','jkl','fgh','WQER']
list_str1=[s for s in list_str if s.isupper()]
list_str2=[s for s in list_str if s.islower()]
print(list_str)
print(list_str1)
print(list_str2)

Example
list1=["abc","123","a123","xyz","x456","789"]
list2=[value for value in list1 if value.isalpha()]
list3=[value for value in list1 if value.isalnum()]
list4=[value for value in list1 if value.isdecimal()]
print(list1)
print(list2)
print(list3)
print(list4)

Q: Write a program to add two matrices using list comprehension.

matrix1=[[1,2],[3,4]]
matrix2=[[5,6],[7,8]]
# without list comprehension
matrix3=[]
for i in range(2):
matrix3.append([])
for j in range(2):
matrix3[i].append(matrix1[i][j]+matrix2[i][j])
# list comprehension
matrix4=[[matrix1[i][j]+matrix2[i][j] for j in range(2)] for i in range(2)]
print(matrix1)
print(matrix2)
print(matrix3)
print(matrix4)
Syntax -3: Nested for loop

List-name=[expression for variable in iterable for variable in iterable]

Without Comprehension:

for variable in iterable:


for variable in iterable:
list-name.append(expression)
# write a program to convert nested list into flat list
list1=[[1,2,3],[4,5,6],[7,8,9]]
# without comprehension
list2=[]
for row in list1:
for col in row:
list2.append(col)

print(list1)
print(list2)
# with comprehension
list3=[col for row in list1 for col in row]
print(list3)

student_list=[['naresh',50,60],['suresh',80,90],['kishore',30,50]]
student_fail_list=[stud[0] for stud in student_list if stud[1]<40 or stud[2]<40]
print(student_list)
print(student_fail_list)

Tuple
Tuple is a list or sequence or iterable.
Tuple is a immutable sequence. Once the tuple is created we cannot
modify(add,update or delete).
Tuples are immutable sequences, typically used to store collections of
heterogeneous data.
Tuples are also used for cases where an immutable sequence of
homogeneous data is needed (such as allowing storage in a set or dict
instance).

How to create tuple?

1. Using a pair of parentheses to denote the empty tuple: ()


2. Using a trailing comma for a singleton tuple: a, or (a,)
3. Separating items with commas: a, b, c or (a, b, c)
4. Using the tuple() built-in: tuple() or tuple(iterable)

T1=(10) # this is not tuple


T2=(10+20) # it represent expression

>>> t1=10,
>>> type(t1)
<class 'tuple'>
>>> t2=(100,)
>>> type(t2)
<class 'tuple'>
>>> t3=1000,2000,300
>>> type(t3)
<class 'tuple'>
>>> t4=(1,2,3,4,5)
>>> type(t4)
<class 'tuple'>

>>> t5=tuple() # empty tuple


>>> t6=() # empty tuple
>>> type(t5)
<class 'tuple'>
>>> type(t6)
<class 'tuple'>
>>> t7=tuple(range(1,11)) # creating tuple using iterable
>>> type(t7)
<class 'tuple'>
>>> t7
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>>
>>> list1=[10,20,30,40,50,60,70]
>>> t8=tuple(list1) # converting list to tuple
>>> list1
[10, 20, 30, 40, 50, 60, 70]
>>> t8
(10, 20, 30, 40, 50, 60, 70)
>>>

Q: What is diff between list and tuple?


List is a mutable collection, after creating list we can add,update and delete
elements.
Tuple is a immutable collection, after creating tuple we cannot add,update
or delete.

>>> l1=[10,20,30]
>>> l1
[10, 20, 30]
>>> l1[0]=100
>>> l1
[100, 20, 30]
>>> t1=(10,20,30)
>>> t1[0]=100
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
t1[0]=100
TypeError: 'tuple' object does not support item assignment
>>>
>>> del l1[0]
>>> l1
[20, 30]
>>> del t1[0]
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
del t1[0]
TypeError: 'tuple' object doesn't support item deletion
>>>
>>> l1.append(90)
>>> l1
[20, 30, 90]
>>> t1.append(90)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t1.append(90)
AttributeError: 'tuple' object has no attribute 'append'
>>>

1. Converting list to dictionary. For this elements of list must be tuple.

2. It is useful when working with functions.


3. Representing immutable list.
4. It is used with functions for representing variable length arguments.
5. It is also used to represent list elements are immutable, when working
with nested list.

Example:
t1=(10,20,30,40,50)
t2=tuple(range(10,60,10))

# reading elements of tuple using index


for i in range(len(t1)):
print(t1[i])

# reading element of tuple using iterator

i=iter(t1)
print(next(i))
print(next(i))
# reading elements of tuple using for loop

for value in t2:


print(value)

# reading elements from tuple using ennumerate

e=enumerate(t1)
print(next(e))
print(next(e))

# representing immutable data within list


student_list=[(101,'naresh','python'),(102,'kishore','cpp')]
for stud in student_list:
print(stud)
del student_list[0][1] # error
Set

A set object is an unordered collection of distinct hashable objects.


A set is non sequence or unordered collection.
A set does not allow duplicate objects or elements.
It is not index based collection or non index based collection, where
reading and writing is not done using index.

Common uses include membership testing, removing duplicates from a


sequence, and computing mathematical operations such as intersection,
union, difference, and symmetric difference.

Set is unordered collection, unordered where insertion order is not


preserved.

List  10 20 30 40 50 60
Set  10 20 30 40 50 60  orders of insertion are done using one data
structure called hashing.

Hashing Data Structure

According to hashing there is a hash table. Each location in hash table is


identified with the key. This key starts with 0. Each location is called bucket.
The bucket contains zero or more values or elements.
Where to add element/item in hash table is defined by hashing alg.

Q: What is hashable object?

An object which contain hash value is called hashable object.


An hash value is integer value, which is used to generate key in hash
based data structures.
If two objects are having same values, they will generate same hash value.
If two objects are equal, they will generate same hash value.
The hash value is an object value which is to check equality.
>>> a=10
>>> hash(a)
10
>>> b=20
>>> hash(b)
20
>>> c=10
>>> hash(c)
10
>>> a==c
True
>>> x=1.5
>>> y=2.5
>>> hash(x)
1073741825
>>> hash(y)
1073741826
>>> x==y
False
>>> z=2.5
>>> hash(z)
1073741826
>>> str1="python"
>>> str2="python"
>>> str1==str2
True
>>> hash(str1)
-337680445
>>> hash(str2)
-337680445
>>> list1=[10,20,30,40,50]
>>> hash(list1)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
hash(list1)
TypeError: unhashable type: 'list'
>>>

Set types are two,


1. Set (mutable)
2. Frozenset (immutable)

How to create set?


1. Set is created by defining elements within curly braces.
{ele,ele,ele,ele,ele,..}
We cannot create empty set using curly braces {} because this curly
braces are used for creating dictionary also. If you define empty curly
braces python create dictionary but not set.

>>> a={}
>>> type(a)
<class 'dict'>
>>> b={10}
>>> type(b)
<class 'set'>

2. Set() type : set type or function is used for creating set.


i. set(): This create empty set
ii. set(iterable) : tis create set using existing iterables
or collections or sequences.

>>> c=set()
>>> d=set([10,20,30,40,50])
>>> c
set()
>>> d
{40, 10, 50, 20, 30}

Set does not allows duplicate objects or elements


>>> x={10,10,10,10,10}
>>> x
{10}
Example:
set1=set(range(10,100,10))
set2=set([10,20,30,40,50])
set3=set("NARESH IT")
print(set1)
print(set2)
print(set3)
set4=set("JAVA")
print(set4)

How read elements from set?


Python allows reading elements from set in different ways.
1. For loop
2. Iterator
Reading elements from set using for loop
set1={10,20,30,40,50}
for n in set1:
print(n)
Reading elements from set using iterator
set1={"naresh","rajesh","suresh","kishore"}
for name in set1:
print(name)
i=iter(set1)
e1=next(i)
e2=next(i)
e3=next(i)
e4=next(i)
print(e1,e2,e3,e4)

Q: What is difference between list and set?


List set
List is a ordered collection. Set is unordered collection.
List is a index based. Set is non index based.
List allows indexing and slicing. Set not allows indexing and
slicing.
List allows duplicate elements. Set not allows duplicate elements
Any object can be added into list Only hashable objects can be
added into set.
The elements are organized in sequential order.
Elements are organized using a
data structure called hashing.
List insertion order is preserved. Set insertion order is not
preserved.
List is a sequence. Set is not sequence.

Mutable methods of set

1. add() : This method is used to add element into set.

# write a program to add elements into set


set1=set()
n=int(input("enter how many elements"))
# adding elements into set
for i in range(n):
ele=int(input("enter element"))
set1.add(ele)
# reading elements from set
for ele in set1:
print(ele)

2. update() : This method is used to add more than one element into set
set1=set()
set1.add(10)
set1.add(20)
print(set1)
set1.update({30,40,50})
print(set1)
set1.update([10,20,30,40,50,60,70,80])
print(set1)
set1.update("PYTHON")
print(set1)
set1.update(range(100,110))
print(set1)

3. remove() : this method is used to remove element from set

set1={10,20,30,40,50}
print(set1)
set1.remove(20)
print(set1)
set1.remove(40)
print(set1)

# Write a program to count how many times each character repeated


with in string.

Input: java
Ouput:1j2a1v

str1=input("Enter any string")


set1=set(str1)
str2=""
for ch in set1:
c=str1.count(ch)
str2=str2+str(c)+ch
print(str1)
print(str2)

Set Operations

1. update(*others)
set |= other | ...
Update the set, adding elements from all others.

Example:
emp_dept10={'naresh','suresh','kishore'}
emp_dept20={'ramesh','rajesh','rakesh'}
print(emp_dept10)
print(emp_dept20)
emp_dept10.update(emp_dept20)
print(emp_dept10)
Example
s1={1,2,3,4,5}
s2={6,7,8}
s1|=s2
print(s1)

2. union(*others)
set | other | ...
Return a new set with elements from the set and all others.

Example
emp_deptno10={'naresh','suresh'}
emp_deptno20={'rajesh','rakesh'}
emp_deptno1020=emp_deptno10.union(emp_deptno20)
print(emp_deptno10)
print(emp_deptno20)
print(emp_deptno1020)

Example
s1={1,2,3,4,5}
s2={1,2,6,7,8}
s3=s1|s2
print(s1)
print(s2)
print(s3)

set1={10,20}
set2={30,40}
set1.update(set2)
print(set1)
print(set2)

3. intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
1. intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.

Example
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.intersection(set2)
print(set1)
print(set2)
print(set3)
set4=set1&set2
print(set4)
s1={1,2,3,4,5}
s2={1,2,6,7,8}
s3={2,3,4,5,6}
s4=s1&s2&s3
print(s1)
print(s2)
print(s3)
print(s4)
Example
python_set={'naresh','suresh','kishore'}
java_set={'suresh','ramesh','rajesh'}
python_java_set=python_set.intersection(java_set)
print(python_set)
print(java_set)
print(python_java_set)

2. difference(*others)
set - other - ...

Return a new set with elements in the set that are not in the others
Example

maths_result={'suresh','naresh','kishore','ramesh','rajesh'}
science_result={'suresh','naresh','kishore','amar','mahesh'}
only_maths=maths_result.difference(science_result)
print(only_maths)
only_science=science_result.difference(maths_result)
print(only_science)
maths_science=maths_result.intersection(science_result)
print(maths_science)

Example
set1={1,2,3,4,5}
set2={1,2,3,6,7}
set3=set1.difference(set2)
print(set1)
print(set2)
print(set3)

Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3={1,2,3,4,7}
s4=s1-s2-s3
print(s1)
print(s2)
print(s3)
print(s4)

3. symmetric_difference(other)
set ^ other

Return a new set with elements in either the set or other but not both.

Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3=s1.symmetric_difference(s2)
print(s1)
print(s2)
print(s3)
s4=s1^s2
print(s4)
Example
set1={'a','b','c','d','e'}
set2={'a','b','f','g','h'}
set3=set1.symmetric_difference(set2)
print(set1)
print(set2)
print(set3)
Example
python_set={'naresh','suresh','kishore','rajesh','sai'}
java_set={'ramesh','rajesh','kiran','naresh','amar'}
only_java_python=python_set^java_set
print(python_set)
print(java_set)
print(only_java_python)

Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3={1,2,3,8,9}
s4=(s1|s2)-(s1|s3)
print(s1)
print(s2)
print(s3)
print(s4)
Example
A={1,2,3,4,5}
B={1,4,5,6,7}
C={2,3,4,8,9}
D=(A|B)&C
print(A)
print(B)
print(C)
print(D)

4. isdisjoint(other)

Return True if the set has no elements in common with other. Sets
are disjoint if and only if their intersection is the empty set.

5. issubset(other)
set <= other
Test whether every element in the set is in other.
6. issuperset(other)
set >= other
Test whether every element in other is in the set.

Example
A={1,2,3,4,5}
B={1,2,3,4,5}
x=A.isdisjoint(B)
print(A)
print(B)
print(x)
S1={1,2,3}
S2={4,5,6}
y=S1.isdisjoint(S2)
print(S1)
print(S2)
print(y)

Example
C={'datatypes','functions','structures'}
CPP={'datatypes','functions','structures','classes','objects'}
if CPP.issuperset(C):
print('C++ is superset of C langauge')
else:
print("C++ is not super set of C language")
Example
C={'datatypes','functions','structures'}
CPP={'datatypes','functions','structures','classes','objects'}
if C.issubset(CPP):
print('C is subset of CPP langauge')
else:
print("C is not suB set of CPP language")

Update methods

update(*others)
set |= other | ...

Update the set, adding elements from all others.

intersection_update(*others)
set &= other & ...

Update the set, keeping only elements found in it and all others.

difference_update(*others)
set -= other | ...

Update the set, removing elements found in others.


symmetric_difference_update(other)
set ^= other

Update the set, keeping only elements found in either set, but not in
both.

A={10}
B={20}
A|=B
Functions which are used on the set.

any() : Return True if any element of the iterable is true. If the iterable is
empty, return False

>>> set1={10,20,30,40,50}
>>> any(set1)
True
>>> set2={False}
>>> any(set2)
False
>>> list1=[False,True]
>>> any(list1)
True
>>> list2=[0,0,0,0,0]
>>> any(list2)
False
>>> set2=set()
>>> any(set2)
False
>>> list2=[]
>>> any(list2)
False
>>>

all(iterable)
Return True if all elements of the iterable are true (or if the iterable is
empty).

>>> l1=[True,False,True]
>>> all(l1)
False
>>> l2=[True,True]
>>> all(l2)
True
>>> s1={True}
>>> all(s1)
True
>>> s2=set()
>>> all(s2)
True

Frozenset

Frozenset is a set.
Forzenset is immutable set. After creating frozenset we cannot do any
changes(add,remove).
Forzenset is hashble type, in application development in order to represent
nested sets or sets with sets we use frozenset.

Syntax:
frozenset([iterable]) : this create frozenset using values from iterable.
If iterable is not supplied it will create empty forzenset.

>>> set1={{1,2,3},{4,5,6}}
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
set1={{1,2,3},{4,5,6}}
TypeError: unhashable type: 'set'
>>> fs1=frozenset()
>>> fs1.add(10)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
fs1.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
>>> s1=set()
>>> s1.add(10)
>>> s1
{10}

>>> fs2=frozenset(range(10,110,10))
>>> fs2
frozenset({100, 70, 40, 10, 80, 50, 20, 90, 60, 30})
>>> fs2=frozenset(['a','b','c','d','e'])
>>> fs2
frozenset({'c', 'd', 'e', 'b', 'a'})
>>> fs3=frozenset((1,2,3,4,5))
>>> fs3
frozenset({1, 2, 3, 4, 5})
>>> fs4=frozenset({10,20,30,40,50})
>>> fs4
frozenset({50, 20, 40, 10, 30})
>>>
Example
set1={frozenset({1,2,3,4,5}),frozenset({1,2,3,4,5})}
print(set1)
set2={frozenset({1,2,3,4,5}),frozenset({6,7,8,9})}
print(set2)
set3={frozenset({1,2,3,4,5}),frozenset({1,2,3,8,9})}
print(set3)

Example
set1={frozenset([10,20,30]),frozenset([40,50,60])}
print(set1)
for s in set1:
for value in s:
print(value,end=' ')
print()

i=iter(set1)
s1=next(i)
s2=next(i)
print(s1)
print(s2)
for value in s1:
print(value,end=' ')

for value in s2:


print(value,end=' ')

Example
python_set={'naresh','suresh','kishore'}
java_set={'suresh','kiran','ramesh','rajesh'}
student_set={frozenset(python_set),frozenset(java_set)}
print(student_set)

Disctionary or Map or dict


Disctionary or Map or dict

Dictionary Is a map collection, where the data is stored as key and value.
Duplicate keys are not allowed but duplicate values are allowed. One key is
mapped with one or more than one value.
Dictionary is a key based collection, where reading and writing is done
using key. Dictionary is mutable collection.

How to create dictionary?

1. We can create dictionary using curly braces {}, this create empty
dictionary.
>>> d1={}
>>> type(d1)
<class 'dict'>
>>> d1
{}
>>>

2. We can create dictionary using curly braces {} with items.


{key:value,key:value,key:value,key:value,…}

Key and values are separated with :


>>> d2={1:'one',2:'two',3:'three'}
>>> type(d2)
<class 'dict'>
>>> d2
{1: 'one', 2: 'two', 3: 'three'}
>>> d3={'a':'apple','b':'ball','c':'cat'}
>>> d3
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
>>>
>>>
d4={2018:[1000,2000,3000,4000,5000],2019:[4000,5000,6000,7000,8000]}
>>> d4
{2018: [1000, 2000, 3000, 4000, 5000], 2019: [4000, 5000, 6000, 7000,
8000]}
>>> type(d4)
<class 'dict'>
>>>
>>> d5={1:100,1:200,1:300}
>>> type(d5)
<class 'dict'>
>>> d5
{1: 300}
>>>
If key is exists update with the value.

3. Creating dictionary using dict type.


a. dict()
b. dict(iterable)

>>> d1=dict()
>>> d1
{}
>>> type(d1)
<class 'dict'>

# creating dictionary using list.

>>> list1=[(1,100),(2,200),(3,300),(4,400),(5,500)]
>>> d1=dict(list1)
>>> d1
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
>>>

# creating dictionary using existing dictionary

>>> d2={1:100,2:200,3:300,4:400,5:500}
>>> d3=dict(d2)
>>> d2
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
>>> d3
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}

# creating dictionary using range or other itrables

zip(): Make an iterator that aggregates elements from each of the iterables
Returns an iterator of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables. The iterator stops when
the shortest input iterable is exhausted.
>>> d4=dict(zip(range(1,6),range(10,60,10)))
>>> d4
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}

>>> names_list=['naresh','suresh','kishore','ramesh']
>>> course_list=['python','oracle','cpp','java']
>>> student_dict=dict(zip(names_list,course_list))
>>> student_dict
{'naresh': 'python', 'suresh': 'oracle', 'kishore': 'cpp', 'ramesh': 'java'}
>>>
>>> str1="PYTHON"
>>> str2="PYTHON"
>>> d5=dict(zip(str1,str2))
>>> d5
{'P': 'P', 'Y': 'Y', 'T': 'T', 'H': 'H', 'O': 'O', 'N': 'N'}
>>> rno=[101,102,103]
>>> names=['ramesh','kishore','naresh']
>>> d6=dict(zip(rno,names))
>>> d6
{101: 'ramesh', 102: 'kishore', 103: 'naresh'}
>>>
How to read content from dictionary?

Python allows to read content of dictionary in different ways.


1. Using key
2. Using iterator
3. Using for loop
4. Items() method
5. keys() method
6. values() method

Example:
product_dict={'mouse':200,'keyboard':2000,'monitor':3000}
print(product_dict['mouse'])
print(product_dict['keyboard'])
print(product_dict['monitor'])
print(product_dict['usb'])# KeyError
Example:
d1={1:100,2:200,3:300,4:400,5:500}
x=iter(d1)
print(next(x)) # return key 1
print(next(x)) # return key 2
print(next(x)) # return key 3
print(next(x))
print(next(x))
y=iter(d1)
key1=next(y)
value1=d1[key1]
key2=next(y)
value2=d1[key2]
print(key1,value1)
print(key2,value2)

z=iter(d1)
for key in z:
print(key,d1[key])
items()

Return a new view of the dictionary’s items ((key, value) pairs).

Example

dict1={1:100,2:200,3:300,4:400,5:500}
x=dict1.items()
print(type(x))
i=iter(x)
item1=next(i)
print(item1)
item2=next(i)
print(item2)
item3=next(i)
print(item3)
item4=next(i)
print(item4)
Example
dict1={1:100,2:200,3:300,4:400,5:500}
x=dict1.items()
for item in x:
print(item)
Example
dict1={1:100,2:200,3:300,4:400,5:500}
for item in dict1.items():
k,v=item # unpacking (1,100)
print(k,v)

keys()

Return a new view of the dictionary’s keys.

dict_courses={'python':4000,'java':2000,'oracle':1000}
courses=dict_courses.keys()
for course in courses:
print(course)

for course,fee in dict_courses.items():#(('python',4000),


print(course,fee)

values()

Return a new view of the dictionary’s values

dict_mailid={'naresh':'naresh.it@gamilcom','suresh':'[email protected]'}
emailid=dict_mailid.values()
for email in emailid:
print(email)

Dictionary is mutable, after creating dictionary we can add, update


and delete items.
Adding items into dictionary

1. Dictionary-name[key]=value : This syntax if the key is not exists it


add new item into dictionary. If key is exists it update the value of
given key.
2. update([other])
Update the dictionary with the key/value pairs from other, overwriting
existing keys. Return None.

# write a program to read details student, each student is having


rollno,name
# organize this data in dictionary

student_dict={}
while True:
rollno=int(input("enter rollno"))
name=input("enter name")
if rollno in student_dict:
print("duplicate keys are not allowed")
else:
student_dict[rollno]=name
ans=input("Add another student?")
if ans=="no":
break

for rollno,name in student_dict.items():


print(rollno,name)

Example
# program which perform two operations
# 1 adding items 2. updating items

products={}
while True:
print("1. Add product")
print("2. Update product")
print("3. Exit")
opt=int(input("enter your option"))
if opt==1:
pname=input("enter product name")
price=float(input("enter price"))
if pname in products:
print("this product exists")
else:
products[pname]=price
elif opt==2:
pname=input("enter product name to update")
price=float(input("enter new price"))
if pname in products:
products[pname]=price
else:
print("product not exists")
elif opt==3:
break

for pname,price in products.items():


print(pname,price)
1. update([other])
Update the dictionary with the key/value pairs from other, overwriting
existing keys. Return None.
Example:
dict1={1:'one',2:'two',3:'three'}
dict2={1:100,2:200,4:400,5:500}
dict2.update(dict1)
print(dict1)
print(dict2)

Example:
deptno10_employees={101:50000,102:60000,103:80000}
deptno20_employees={104:70000,105:25000,106:35000}
employee_dict={}
employee_dict.update(deptno10_employees)
employee_dict.update(deptno20_employees)
print(deptno10_employees)
print(deptno20_employees)
print(employee_dict)

2. del d[key]

Remove d[key] from d. Raises a KeyError if key is not in the map.

3. clear()

Remove all items from the dictionary

dict1={1:100,2:200,3:300,4:400}
print(dict1)
del dict1[1]
print(dict1)
del dict1[1]

dict1={1:100,2:200,3:300,4:400}
print(dict1)
dict1.clear()
print(dict1)

Develop Address Book


Key Value
Name [houseno,street,city]

String List

**Address Book***

1. Add Address
2. Update Address
3. Delete Address
4. Search Address
5. List Addresses
6. Exit

Enter Your Option:

Case Study

address_book={}
while True:
print("***Address Book***")
print("1. Add Address")
print("2. Update Address")
print("3. Delete Address")
print("4. Search Address")
print("5. List Addresses")
print("6. Exit")
opt=int(input("enter option"))
if opt==1:
name=input("Enter Name")
hno=input("Enter HouseNo")
street=input("Enter Street")
city=input("Enter City")
l=[hno,street,city]
if name in address_book:
print("Address with this name exists")
ans=input("overwrite existing address")
if ans=='yes':
address_book[name]=l
else:
address_book[name]=l
elif opt==2:
name=input("Enter name to update")
if name in address_book:
hno=input("Enter hno")
street=input("Enter street")
city=input("Enter city")
address_book[name]=[hno,street,city]
else:
print("Input name not exists")
elif opt==3:
name=input("Enter name to delete")
if name in address_book:
del address_book[name]
print("Address Deleted")
else:
print("name not exists")
elif opt==4:
name=input("Enter name")
if name in address_book:
l=address_book[name]
print("Hno :",l[0])
print("Street :",l[1])
print("City :",l[2])
else:
print("name not eixsts")
elif opt==5:
for name,l in address_book.items():
print(name,l[0],l[1],l[2])
elif opt==6:
break

We cannot define dictionary inside dictionary(nested dictionary), but value


of dictionary can be of type dictionary.
Example:
>>> dict2={1:{'a':'apple'},2:{'b':'ball'}}
>>> dict2
{1: {'a': 'apple'}, 2: {'b': 'ball'}}

Example
dict1={2019:{'jan':10000,'feb':20000},2020:{'jan':30000,'feb':34000}}
print(dict1)
for year,sales in dict1.items():
print(year,sales)
for month,sale in sales.items():
print(month,sale)
Dictionary Comprehension

Comprehension is process of creating collection using for loop, iterables


and conditions.

Dictionary comprehension allows to create new dictionary using existing


dictionary or iterables with help of for loop and condition.

Syntax1: {key:value for variable in iterable}


Syntax2: {key:value for variable in iterable if test}
Syntax3:{key:value for variable in iterable for variable in iterable}
Syntax4:{key:value for variable in iterable for variable in iterable if test}

Dictionary comprehension provide an elegant way of creating dictionary.

Example
dict1={1:10,2:20,3:30,4:40,5:50}
dict2={}
# without comprehension
for key,value in dict1.items():
dict2[key]=value

print(dict1)
print(dict2)

# with comprehension
dict3={key:value for key,value in dict1.items()}
print(dict3)

Example
# create dictionary where store key as number value as squre of that
number
# without comprehension
dict1={}
for num in range(1,11):
dict1[num]=num**2
print(dict1)
# with comprehension

dict2={num:num**2 for num in range(1,11)}


print(dict2)

# comprehension with if condition/test


student_dict={'naresh':'A','suresh':'A','kishore':'B','ramesh':'C',
'rajesh':'C','kiran':'B'}
print(student_dict)
student_dictA={name:grade for name,grade in student_dict.items() if
grade=='A'}
student_dictB={name:grade for name,grade in student_dict.items() if
grade=='B'}
student_dictC={name:grade for name,grade in student_dict.items() if
grade=='C'}
print(student_dictA)
print(student_dictB)
print(student_dictC)

Q: What is different between list,set and dictionary/map?

List Set Dictionary


List is a index based Set is non index based Dictionary key based
Collection collection collection
Reading and writing of Reading and writing of Reading and writing of
elements are done elements are not done elements are done
using index using index using key
Duplicate elements are Duplicate elements are Duplicate keys are not
allowed not allows allowed but duplicate
values are allowed
It is ordered collection, It is unordered It is ordered collection
where insertion order is collection where where insertion order is
preserved insertion ordered is not preserved
preserved.
Any values can be Only hashble objects Key must be hashble
added into list can be added into set and values can be any
type
When application When application When application
require to store required store objects, required to store the
duplicate objects and where duplicate s are data as key and value
insertion order should not allowed go for set. It pair then go for map
be preserved go for list. also provide collection.
mathematical set
operations
The elements are The elements are The elements are
organized in sequential organized using organized using key
order hashing data structure and value pair.

Functions

Python is a multiparadigm programming language. A programming


paradigm define set of rules and regulations for organization of data and
instructions.
In python we can write a program using different programming approaches.
1. Unstructured Programming
2. Procedural Oriented Programming
3. Modular Oriented Programming
4. Object Oriented Programming
5. Functional Oriented Programming

Unstructured programming instructions are organized in sequential order.


Sequence is set of instructions used to solve given problem.
DisAdv:
There is no code reusability. Where there is no code reusability the size of
program increase, which occupy more space and efficiency is decreased.
Strings

String is a collection of characters. These characters can be alphabets,


digits or special characters. The string which contains only alphabets is
called alphabetic string. The string which contains alphabets and digits is
called alpha numeric string.

String is a sequence data type.


‘str’ is class or data type which is used to represent string object.

How to represent string in python?


1. Within single quotes ‘ ‘
2. Within double quotes “ “
3. Within three single quotes or double quotes
4. str() type
within single quotes we can embed double quotes
within double quotes we can embed single quotes
within triple quotes we can represent multiline string. Within three single
quotes we can embed double quotes and within three double quotes we
can embed single quotes.
Example
str1='This is single line string'
str2="This is single line string"
str3="""This is multiline string
This is multiline string"""
print(str1)
print(str2)
print(str3)
str4="this is 'python' langauge"
str5='this is "python" language'
print(str4)
print(str5)
str6=str(100) # used to convert integer to string
str7=str(1.5) # used to convert float to string
str8=str(1+2j) # used to conver complex to string
str9=str("Python")
print(str6)
print(str7)
print(str8)
print(str9)

String is an immutable sequence. Once the string is created we cannot do


changes. String is index based like list.
String is immutable because of this it is shared.

>>> str1="python"
>>> str2="python"
>>> id(str1)
53609440
>>> id(str2)
53609440
>>> str1="R"
>>> id(str1)
14342400
>>> str2[0]="P"
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
str2[0]="P"
TypeError: 'str' object does not support item assignment
>>>

How to read content of string?

1. Index
2. Slicing
3. For loop
4. Iterator

Using index we can read only one character from string. Index allows to
read in sequential and random order. Like list string can be read using +ve
and –ve index.

Example

str1="PYTHON"
for i in range(len(str1)): # 0 1 2 3 4 5
print(str1[i],end=' ')

print()
for i in range(-len(str1),0): # -6 -5 -4 -3 -2 -1
print(str1[i],end=' ')
print()
for i in range(-1,-(len(str1)+1),-1): # -1 -2 -3 -4 -5 -6
print(str1[i],end=' ')
print()
for i in range(len(str1)-1,-1,-1): # 5 4 3 2 1 0
print(str1[i],end=' ')
string slicing
using slicing we can read a part of string. Slicing is done using slice
operator we required start index, stop index and step. It allows to more than
one character from string.
String-name[start:stop:step]
Default start is 0 and stop is len(string) and step is +1
For –ve step default start is -1 and default stop –len(string)

Example
str1="PYTHON"
str2=str1[::]
print(str1)
print(str2)
str3=str1[::-1]
print(str3)
Example
str1="PROGRAMMING"
str2=str1[:]
str3=str1[::-1]
str4=str1[::2]
str5=str1[::-2]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
str6=str1[3:8]
print(str6)
str7=str1[-4:-7:-1]
print(str7)

Example
# write a program to find input string is pal or not
str1=input("enter any string")
str2=str1[::-1]
if str1==str2:
print("pal ")
else:
print("not pal")

# this read each time one character from string

str1="PROGRAMMING"
for ch in str1:
print(ch,end='')

# reading string using iterator


str1="PYTHON"
i=iter(str1)
ch1=next(i)
ch2=next(i)
ch3=next(i)
print(ch1,ch2,ch3)
for ch in i:
print(ch)
String Methods

String Conversion Methods


str.capitalize() str1="PROGRAMMING"
str2="programming"
Return a copy of the string with str3=str1.capitalize()
its first character capitalized str4=str2.capitalize()
and the rest lowercased. print(str1)
print(str2)
print(str3)
print(str4)
str.lower() namesList=['NARESH','SURESH','RAJES
Return a copy of the string with H']
all the cased characters for name in namesList:
converted to lowercase print(name.lower())
str.swapcase() >>> str1="RAMESH"
Return a copy of the string with >>> str1.swapcase()
uppercase characters 'ramesh'
converted to lowercase and >>> str2="ramesh"
vice versa. >>> str2.swapcase()
'RAMESH'
>>> str3="rAMESH"
>>> str3.swapcase()
'Ramesh'
str.title() >>> str1="python is a programming
Return a titlecased version of language"
the string where words start >>> str1.title()
with an uppercase character 'Python Is A Programming Language'
and the remaining characters
are lowercase
str.upper() >>> str1="python"
Return a copy of the string with >>> str1.upper()
all the cased characters 'PYTHON'
converted to uppercase.

String examine methods


str.isalnum() >>> str1="python"
Return True if all characters in the >>> str1.upper()
string are alphanumeric and there is 'PYTHON'
at least one character, False >>> uname="nit123"
otherwise >>> uname.isalnum()
True
>>> str1="nit"
>>> str1.isalnum()
True
>>> str2="123"
>>> str2.isalnum()
True
>>> str3="$%"
>>> str3.isalnum()
False
>>> str4="nit$"
>>> str4.isalnum()
False
str.isalpha() >>> name="naresh"
Return True if all characters in the >>> name.isalpha()
string are alphabetic and there is at True
least one character, False otherwise >>> name="naresh1"
>>> name.isalpha()
False
str.isdecimal() >>> s1="65"
Return True if all characters in the >>> s1.isdecimal()
string are decimal characters and True
there is at least one character, False >>> s2="0o12"
otherwise. >>> s2.isdecimal()
False
str.islower() >>> s1="naresh"
Return True if all cased characters >>> s1.islower()
in the string are lowercase and there True
is at least one cased character, >>> s2.islower()
False otherwise. False

str.isnumeric() >>> s1="65"


Return True if all characters in the >>> s1.isnumeric()
string are numeric characters, and True
there is at least one character, False >>> s2="1.5"
otherwise. >>> s2.isnumeric()
False
str.isspace() >>> uname="naresh 123"
Return True if there are only >>> uname.isspace()
whitespace characters in the string False
and there is at least one character, >>> str1=""
False otherwise. >>> str1.isspace()
False
>>> str2=" "
>>> str2.isspace()
True
str.istitle() >>> str1="Naresh Technologies"
Return True if the string is a >>> str1.istitle()
titlecased string and there is at least True
one character >>> str2="python language"
>>> str3.istitle()
False
str.isupper() >>> str1="naresh"
Return True if all cased characters >>> str1.isupper()
in the string are uppercase and False
there is at least one cased >>> str2="NARESH"
character, False otherwise. >>> str2.isupper()
True
>>>

String join method


str.join(iterable) namesList=["naresh","rajesh","suresh","kishore"]
Return a string which is >>> "-".join(namesList)
the concatenation of the 'naresh-rajesh-suresh-kishore'
strings in iterable. The >>> ",".join(namesList)
separator between 'naresh,rajesh,suresh,kishore'
elements is the string
providing this method.
String justification methods
str.ljust(width[, fillchar]) namesList=["naresh","suresh","ram","kishore"]
Return the string left for name in namesList:
justified in a string of print(name.ljust(15),name)
length width. Padding is
done using the specified for name in namesList:
fillchar print(name.ljust(15,"*"),name)
str.rjust(width[, fillchar]) namesList=["naresh","suresh","ram","kishore"]
Return the string right for name in namesList:
justified in a string of print(name.rjust(15),name)
length width. Padding is
done using the specified for name in namesList:
fillchar print(name.rjust(15,"*"),name)
String splitting methods
str.split(sep=None, maxsplit=-1) >>> str1="a,b,c,d,e,f"
Return a list of the words in the >>> str1.split(",")
string, using sep as the delimiter ['a', 'b', 'c', 'd', 'e', 'f']
string. If maxsplit is given, at most >>> str1.split(",",2)
maxsplit splits are done (thus, the ['a', 'b', 'c,d,e,f']
list will have at most maxsplit+1
elements). If maxsplit is not
specified or -1, then there is no limit
on the number of splits
str.rsplit(sep=None, maxsplit=-1) >>> str1="a,b,c,d,e,f"
Return a list of the words in the >>> str1.rsplit(",")
string, using sep as the delimiter ['a', 'b', 'c', 'd', 'e', 'f']
string. If maxsplit is given, at most >>> str1.rsplit(",",2)
maxsplit splits are done, the ['a,b,c,d', 'e', 'f']
rightmost ones. If sep is not
specified or None, any whitespace
string is a separator.
str.partition(sep) >>> str1="python,language"
Split the string at the first occurrence >>> str1.partition(",")
of sep, and return a 3-tuple ('python', ',', 'language')
containing the part before the >>> str1="abc"
separator, the separator itself, and >>> str1.partition("b")
the part after the separator. If the ('a', 'b', 'c')
separator is not found, return a 3-
tuple containing the string itself,
followed by string itself.
str.rpartition(sep) >>> str1="abdcde"
Split the string at the last occurrence >>> str1.rpartition("d")
of sep, and return a 3-tuple ('abdc', 'd', 'e')
containing the part before the >>> str1.partition("d")
separator, the separator itself, and ('ab', 'd', 'cde')
the part after the separator. If the >>>
separator is not found, return a 3-
tuple containing two empty strings,
followed by the string itself.

Finding and replacing method


str.rfind(sub[, start[, end]]) >>> str1="python java python java"
Return the highest index in the string >>> str1.rfind("java")
where substring sub is found, such 19
that sub is contained within >>> str1.rfind("c")
s[start:end]. Optional arguments -1
start and end are interpreted as in
slice notation. Return -1 on failure.
str.find(sub[, start[, end]]) >>> str1="python java python java"
Return the lowest index in the string >>> str1.find("java")
where substring sub is found within 7
the slice s[start:end]. Optional
arguments start and end are
interpreted as in slice notation.
Return -1 if sub is not found.
str.replace(old, new[, count]) >>> str1="abcabcabc"
Return a copy of the string with all >>> str1.replace("a","A")
occurrences of substring old 'AbcAbcAbc'
replaced by new. If the optional >>> str1.replace("a","A",1)
argument count is given, only the 'Abcabcabc'
first count occurrences are replaced. >>> str1.replace("a","A",2)
'AbcAbcabc'
>>>

You might also like