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

Module 2 Ppt

The document covers various data types in Python, focusing on lists, dictionaries, and string manipulation. It explains list properties, methods for adding and removing elements, and provides examples of list operations such as concatenation, slicing, and sorting. Additionally, it includes practical projects to apply these concepts, such as creating a Magic 8 Ball and a Password Locker.

Uploaded by

Prajwal Srinath
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)
7 views

Module 2 Ppt

The document covers various data types in Python, focusing on lists, dictionaries, and string manipulation. It explains list properties, methods for adding and removing elements, and provides examples of list operations such as concatenation, slicing, and sorting. Additionally, it includes practical projects to apply these concepts, such as creating a Magic 8 Ball and a Password Locker.

Uploaded by

Prajwal Srinath
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/ 75

MODULE-2

CONTENTS
• Lists: The List Data Type, Working with Lists, Augmented Assignment
Operators, Methods, Example Program: Magic 8 Ball with a List,
List-like Types: Strings and Tuples, References,

• Dictionaries and Structuring Data: The Dictionary Data Type, Pretty


Printing, Using Data Structures to Model Real-World Things,

• Manipulating Strings: Working with Strings, Useful String Methods,


Project: Password Locker, Project: Adding Bullets to Wiki Markup
CHAPTER 1-LISTS
• List datatype : collection of homogenous or heterogenous values.

• It can contain values of all python valid datatypes

• The vales should be enclosed within [ ],separated by comma(,)

• The order in which the values are inserted ,will be preserved.

• List is mutual datatype,(values can be modified)

• It supports both +ve and –ve indexing

• Syntax: variable=[val1,val2,………..valN]
Examples:
• >>> [10,20,30]
[10, 20, 30]
• >>> lst1=[10,20,30]
• >>> lst1
[10, 20, 30]
• >>> type(lst1)
<class 'list’>
• >>> id(lst1)
2521788515584 -ve index -4 -3 -2 -1
• >>> lst2=[10,20.5,3+5j,'hello'] 10 20.5 (3+5j) ‘Hello’
• >>> lst2 +ve index 0 1 2 3
[10, 20.5, (3+5j), 'hello']
• >>> lst2[0] Accessing elements in the inner collection
10  lst3=[10,20.5,3+5j,'hello']

• lst2[-4]  >>> lst3


[10, 20.5, (3+5j), 'hello']
10
 >>> lst3[3][0]
• >>> lst2[2]
‘h’
(3+5j)  >>> lst4=[[50,60],10,'python']
• >>> lst2[-1]  >>> lst4[0]
'hello' [50, 60]
• >>> lst2[3]  >>> lst4[0][0]
'hello’ 50

• lst2[5]  >>> lst4[0][1]

Traceback (most recent call last): 60

File "<pyshell#26>", line 1, in LISTS are mutable


<module>  >>> lst3[2]=200
lst2[5]  >>> lst3

IndexError: list index out of range [10, 20.5, 200, 'hello']


List Concatenation (+)
• >>> lst3=lst3+[[20,30]]  >>> lst5+=[10]
• >>> lst3  >>> lst5
[10, 20.5, 200, 'hello', [20, 30]] [10]
• >>> lst3+=[3+5j]  >>> lst5+=[20.5]
• >>> lst3  >>> lst5
[10, 20.5, 200, 'hello', [20, 30], (3+5j)] [10, 20.5]
• lst5=[ ]  >>> lst5+=[3+5j]
• >>> lst5  >>> lst5
[] [10, 20.5, (3+5j)]

• >>> lst5+=10  >>> lst5+=['hello']

Traceback (most recent call last):  >>> lst5

File "<pyshell#15>", line 1, in [10, 20.5, (3+5j), 'hello']


<module>  >>> lst5+=[[10,20]]
lst5+=10  >>> lst5
TypeError: 'int' object is not iterable [10, 20.5, (3+5j), 'hello', [10, 20]]
List Replication(*)
• lst3=[20,3+5j,'hello']
• >>> lst3=lst3*2
• >>> lst3
[20, (3+5j), 'hello', 20, (3+5j), 'hello’]
• >>> lst3[2]
'hello'
• >>> lst3[5]
'hello’
• >>> lst3[2][0]
'h'
• >>> lst3[5][0]
'h'
SLICING(STRINGS)
Using +ve index  Using -ve index  Reversing string
• >>> name[0:3]  >>> len(name)  >>> name='python'
'pyt' 6  >>> name[-1:-7:-1]
• >>> name[3]  >>> name[-6:-1:1] 'nohtyp’
'h' 'pytho'  >>> name[-1::-1]
• >>> name[:3]  >>> name[-6:0:1] 'nohtyp’
'pyt' ''
• >>> name[:3:1]  >>> name[-6:0] ACCESING CHARACTERS
'pyt’ ''  >>> name[::2]
• >>> name[::]  >>> name[-6:-1:-1] 'pto’
'python’ ''  >>> name[-1::-2]
• >>>  >>> name[-6:] 'nhy'
name[0:len(name):1] 'python’
'python'
SLICING(LIST)
• >>>  >>> lst[::2]
lst=[10,20.5,3+5j,'python',[10,20]]
[10, (3+5j), [10, 20]]
• >>> len(lst)
5
 >>> lst[-1:-len(lst)-1:-1]
[[10, 20], 'python', (3+5j), 20.5, 10]
• >>> lst[:len(lst):]
[10, 20.5, (3+5j), 'python', [10, 20]]
 >>> lst[::]

• >>> lst[1::] [10, 20.5, (3+5j), 'python', [10, 20]]

[20.5, (3+5j), 'python', [10, 20]]


 >>> lst[2:4]
• >>> lst[:4:] [(3+5j), 'python']
[10, 20.5, (3+5j), 'python']
Displaying elements of the list
Using index( ) Method Using index( ) Method
Using index
 >>>  >>> lst.index(10)
• >>> lst[0] lst=['cat','bat','rat',20,3+5j,[10,2 Traceback (most recent call last):
10 0]]
File "<pyshell#6>", line 1, in <module>
• >>> lst[-5]  >>> lst
lst.index(10)
10 ['cat', 'bat', 'rat', 20, (3+5j), [10, 20]]
ValueError: 10 is not in list
• >>> lst[2]  >>> lst.index('cat')
 >>> lst.index([10,20])
(3+5j) 0
5
• >>> lst[-3]  >>> lst.index('rat')
 >>> lst.index([10])
(3+5j) 2
Traceback (most recent call last):
>>> lst[4][0]  >>> lst.index(3+5j) File "<pyshell#8>", line 1, in <module>
10 4 lst.index([10])
>>> lst[-1][0] ValueError: [10] is not in list
10
ADDING VALUES TO THE LIST
USING +(CONCATINATION) USING +(CONCATINATION)

• >>> lst2=[10]  >>> list('hello')


• >>> lst2=lst2+[30] ['h', 'e', 'l', 'l', 'o']
• >>> lst2  >>> lst2=lst2+list('hello')
[10, 30]  >>> lst2
• >>> lst2=lst2+30.5
[10, 30, 30.5, 'h', 'e', 'l', 'l', 'o’]
Traceback (most recent call last):
 >>> lst2=lst2+list(30.5)
File "<pyshell#3>", line 1, in <module>
lst2=lst2+30.5 Traceback (most recent call last):
TypeError: can only concatenate list (not "float") to list File "<pyshell#12>", line 1, in <module>
• >>> lst2=lst2+[30.5] lst2=lst2+list(30.5)
• >>> lst2 TypeError: 'float' object is not iterable
[10, 30, 30.5]
USING append() and insert()
• >>> lst1=[10,20.5] Without using insert()
• >>> lst1.append('hello')  >>> lst1
• >>> lst1 [10, 20.5, 'hello’]
[10, 20.5, 'hello’]

 >>> lst1[:1]+[3+5j]+lst1[2:]
• >>> lst1.insert(2,3+5j)
[10, (3+5j), 'hello']
• >>> lst1
[10, 20.5, (3+5j), 'hello’]
• >>> lst1.insert(3,[10,20])
• >>> lst1
[10, 20.5, 'hello', [10, 20]]
• >>> lst1=[10,20.5] NOTE:
• >>> id(lst1)  The append() and insert() methods are list methods and
2359063158272 can be called only on list values, not on other values such
as strings or integers.
• >>> lst1.append('hello')
 >>> num=20
• >>> lst1
 >>> num.insert(1,20)
[10, 20.5, 'hello'] Traceback (most recent call last):
• >>> id(lst1) File "<pyshell#9>", line 1, in <module>
2359063158272 num.insert(1,20)
• >>> lst1.insert(2,4+7j) AttributeError: 'int' object has no attribute 'insert’
• >>> lst1
[10, 20.5, (4+7j), 'hello']  >>> str1='hello'
• >>> id(lst1)  >>> str1.insert(3,'y')
2359063158272 Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
NOTE:
str1.insert(3,'y')
• The return value of append() and insert() is
None, so you definitely wouldn’t want to AttributeError: 'str' object has no attribute 'insert'
store this as the new variable value.
Finding a Value in a List with the index() Method
>>> lst1=[10,20,30.5,'pyhton']
>>> lst1.index(20)
1

>>> lst1.index('pyhton’)
3

>>> lst1.index(5j)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
lst1.index(5j)
ValueError: 5j is not in list
Removing Values from Lists
Using del statement Using remove( ) method
• lst1=[10,20,30.5,’python’]  >>> lst1=[10,20.5,4+5j,'hello']
 >>> lst1
• del lst1[0] [10, 20.5, (4+5j), 'hello’]
• >>> lst1
[20, 30.5, ‘python’]
 >>> len(lst1)
4
• >>> len(lst1)
3
• >>> lst1  >>> lst1.remove(20.5)
[20, 30.5, ‘python’]  >>> lst1
[10, (4+5j), 'hello’]
• >>> lst1=[10,20.5,4+5j,'hello’]
 >>> len(lst1)
• >>> lst1 3
[10, 20.5, (4+5j), 'hello']
• >>> del lst1[lst1.index(10)]  >>> lst1.remove(lst1[1])
• >>> lst1
 >>> lst1
[20.5, (4+5j), 'hello']
[10, 'hello']
Sorting the Values in a List using sort()
>>> lst1=[20,4,8,10,30]  >>> lst1=['c','B','d','D','A']
>>> lst1.sort()  >>> lst1.sort()
>>> lst1  >>> lst1
[4, 8, 10, 20, 30] ['A', 'B', 'D', 'c', 'd’]

>>> lst1=[10,20.5,15.6,34,25.6]  >>> lst1=['5','8','6','3']


>>> lst1.sort()  >>> lst1.sort()

>>> lst1  >>> lst1

[10, 15.6, 20.5, 25.6, 34] ['3', '5', '6', ‘8’]

 >>> lst1=[20,12,'a','m','g']
>>>
lst1=['alpha','beta','delta','creta','jaquar','kent']  >>> lst1.sort()
>>> lst1.sort() Traceback (most recent call last):
>>> lst1 File "<pyshell#16>", line 1, in <module>

['alpha', 'beta', 'creta', 'delta', 'jaquar’, 'kent'] lst1.sort()


TypeError: '<' not supported between instances of 'str' and 'int'
Note 1: You can also pass True for Note 2: If you need to sort the values in regular alphabetical
order, pass str.lower for the key keyword argument in the
the reverse keyword argument to sort() method call.
h ave s o r t ( ) s o r t t h e va l u e s i n
reverse order  >>> lst1=['a','b','A','B','z','M']
 >>> lst1.sort()

>>> lst1=[23,45,38,7]  >>> lst1


['A', 'B', 'M', 'a', 'b', 'z']
>>> lst1.sort()
>>> lst1  >>> lst1.sort(key=str.lower)
[7, 23, 38, 45]  >>> lst1
['A', 'a', 'B', 'b', 'M', ‘z’]
OR
>>> lst1.sort(reverse=True) >>> lst1.sort(key=str.upper)
>>> lst1 >>> lst1

[45, 38, 23, 7] ['A', 'a', 'B', 'b', 'M', 'z']


Reversing the Values in a List with the reverse() Method
>>> lst1
['A', 'a', 'B', 'b', 'M', 'z’]

>>> lst1.reverse()
>>> lst1
['z', 'M', 'b', 'B', 'a', ‘A’]

>>> lst1=[25,10,35,50,8]
>>> lst1.reverse()
>>> lst1
[8, 50, 35, 10, 25]
Using for Loops with Lists
PROGRAM: Output:
enter number of animals5
n=int(input('enter number of
enter 5 animal names
animals'))
enter 1 animal name
print('enter',n,'animal names') lion
animal_names=[ ] enter 2 animal name
for i in range(n): tiger
enter 3 animal name
print('enter',i+1,'animal
name’) dog
enter 4 animal name
a_name=input() cow
animal_names+=[a_name] enter 5 animal name
rabbit

print(animal_names) ['lion', 'tiger', 'dog', 'cow', 'rabbit']


WHILE LOOP FOR LIST
PROGRAM OUTPUT:

n=int(input('enter number of animals')) enter number of animals4


enter 4 animal names
print('enter',n,'animal names')
enter 1 animal name
animal_names = [] tiger
i=0 enter 2 animal name
while i<n: lion
print('enter',i+1,'animal name') enter 3 animal name

aname = input() rabbit


enter 4 animal name
animal_names = animal_names + [aname]
cow
i+=1 The cat names are:
tiger
print('The cat names are:') lion
for aname in animal_names: rabbit

print( aname) cow


The in and not in Operators
• You can determine whether a value is or isn’t in a list with the in and not in operators.

• Like other operators, in and not in are used in expressions and connect two values: a value to
look for in a list and the list where it may be found.
• These expressions will evaluate to a Boolean value.

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']


True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
PROGRAM: OUTPUT:

myPets = ['Zophie', 'Pooka', 'Fat-tail'] Enter a pet name:

print('Enter a pet name:') Footfoot

name = input() I do not have a pet named Footfoot

if name not in myPets:


print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Linear search
n=int(input('enter number of animals')) Output:

print('enter',n,'animal names') enter number of animals4


animal_names = [ ] enter 4 animal names
i=0 enter 1 animal name
flag=False
tiger
while i<n:
enter 2 animal name
print('enter',i+1,'animal name')
lion
aname = input()
enter 3 animal name
animal_names = animal_names + [aname]
elephant
i+=1
enter 4 animal name

cow
print('The animal names are:')
The animal names are:
print( animal_names)
['tiger', 'lion', 'elephant', 'cow']
print(‘enter your pet animal:')
enter your pet animal namecow
petanimal=input()

for animal in animal_names : cowpresent in the list

if animal==petanimal:

flag=True

break

if flag==True:

print(petanimal+'present in the list')

else:

print(petanimal+' not present in the list')


The Multiple Assignment Trick
Values of list to VARIABLES
 >>> list1=[20,36.5,'hello',5j]

LIST of values to  >>> list1


[20, 36.5, 'hello', 5j]
VARIABLES  >>> a,b,c,d=list1
>>> x,y,z=10,20,30  >>> a
20
>>> x  >>> b
10 36.5
 >>> c
>>> y 'hello'

20  >>> d
5j
>>> z  >>> a,b,c,d,e=list1

30 Traceback (most recent call last):


File "<pyshell#8>", line 1, in <module>
a,b,c,d,e=list1
ValueError: not enough values to unpack (expected 5, got 4)
Using the enumerate() Function with Lists
• Instead of using the range(len(someList)) technique with a for loop to obtain the integer
index of the items in the list, you can call the enumerate() function instead.
• On each iteration of the loop, enumerate() will return two values: the index of the
item in the list, and the item in the list itself.
• The enumerate() function is useful if you need both the item and the item’s index in
the loop’s block.

>>> pet_animals=['cat','cow','dog','sheep','goat']
>>> for index,item in enumerate(pet_animals):
print("index", index," is having animal:", item)

Output:
index 0 is having animal: cat
index 1 is having animal: cow
index 2 is having animal: dog
index 3 is having animal: sheep
index 4 is having animal: goat
Functions in random module for list
Using random.choice( ) Using random.shuffle()
 The random.shuffle() function will reorder the items in a list. This
>>> import random function modifies the list in place, rather than returning a new list
>>>pet_animals=['cat','cow','dog','sheep','goat'] >>> import random
>>>pet_animals=['cat','cow','dog','sheep','goat']
>>> random.choice(pet_animals)
>>> print(pet_animals)
'dog’
['cat', 'cow', 'dog', 'sheep', 'goat']
>>> random.choice(pet_animals) >>> random.shuffle(pet_animals)
'goat' >>> print(pet_animals)
>>> random.choice(pet_animals) ['goat', 'sheep', 'cat', 'dog', 'cow’]
>>> id(pet_animals)
'cow'
1820284294528
>>> random.choice(pet_animals)
>>> random.shuffle(pet_animals)
'cat' >>> print(pet_animals)
['sheep', 'goat', 'dog', 'cow', 'cat']
>>> id(pet_animals)
1820284294528
Magic 8 Ball with a List
PROGRAM: Output:
import random My reply is no
messages = ['It is certain’,
'It is decidedly so’,
'Yes definitely’, Yes definitely
'Reply hazy try again’,
'Ask again later’,
'Concentrate and ask again’,
'My reply is no','Outlook not so good’,
'Very doubtful']
print(messages[random.randint(0, len(messages) - 1)])
Sequence Data Types
• The Python sequence data types include lists, strings, range objects
returned by range(), and tuples

• Many of the things you can do with lists can also be done with strings and
other values of sequence types: indexing; slicing; and using them with
for loops, with len(), and with the in and not in operators.
Mutable and Immutable Data Types
• A list value is a mutable data type: it can have values added, removed, or
changed.
• However, a string is immutable: it cannot be changed. Trying to reassign a single
character in a string results in a TypeError error,
 Examples: (on strings)  Proper way to modify(slicing and concate)
>>> name="bangalore" >>> name="bangalore"
>>> name[2] >>> name[2]
'n' 'n’
>>> name[2]='m'
>>> name=name[0:2]+'m'+name[3:]
Traceback (most recent call last):
>>> name
File "<pyshell#2>", line 1, in <module>
'bamgalore’
name[2]='m'
>>> name[2]
TypeError: 'str' object does not support item
assignment 'm'
 Examples: LIST Example 3:
Example 1: >>> pet_animals=['cat','cow','sheep','goat']

>>> pet_animals=['cat','cow','sheep','goat'] >>> pet_animals=pet_animals[:2]+['dog']+pet_animals[2:]


>>> pet_animals
>>> pet_animals
['cat', 'cow', 'dog', 'sheep', 'goat']
['cat', 'cow', 'sheep', 'goat']
>>> pet_animals[2]
>>> pet_animals[2]
'dog’
'sheep'
>>> pet_animals[2]='bull' Example 4:
>>> pet_animals
['cat', 'cow', 'bull', 'goat’] >>> pet_animals=[]
>>> pet_animals[2] >>> pet_animals
'bull’ []
>>> pet_animals.append('cat')

Example 2: >>> pet_animals


['cat']
>>> pet_animals=pet_animals[0:2]+['bull']+pet_animals[3:]
>>> pet_animals.append('dog')
>>> pet_animals
>>> pet_animals
['cat', 'cow', 'bull', 'goat']
['cat', 'dog']
The Tuple Data Type
• The tuple data type is almost identical to the list data type, except in two ways.
• First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].
• The main way that tuples are different from lists is that tuples, like strings, are
immutable. Tuples cannot have their values modified, appended, or removed.
Examples Examples(immutable)
>>> animals=() >>> animals=('cat','dog','tiger’)
>>> animals >>> type(animals)
() <class 'tuple'>
>>> animals=(10)
>>> animals
>>> animals
('cat', 'dog', 'tiger')
10
>>> animals[2]
>>> type(animals)
'tiger'
<class 'int'>
>>> animals=(10,)
>>> animals[2]='cow'
>>> animals Traceback (most recent call last):
(10,) File "<pyshell#3>", line 1, in <module>
>>> type(animals) animals[2]='cow'
<class 'tuple'> TypeError: 'tuple' object does not support item assignment
Converting Types with the list() and tuple() Functions
>>> sample_list=[10,20.5,5j,'cat',[10,20]] >>> name="hello"
>>> type(sample_list) >>> type(name)
<class 'list'>
<class 'str’>
>>> tuple(sample_list)
(10, 20.5, 5j, 'cat', [10, 20]) >>> str_lst=list(name)
>>> sample_tuple=tuple(sample_list) >>> str_lst
>>> sample_tuple ['h', 'e', 'l', 'l', 'o']
(10, 20.5, 5j, 'cat', [10, 20]) >>> str_tpl=tuple(name)
>>> sample_tuple[2]
>>> str_tpl
5j
('h', 'e', 'l', 'l', 'o')
>>> len(sample_tuple)
5
>>> type(sample_tuple)
<class 'tuple'>
>>> sample_tuple[4][0]
10
>>> num=10
References
>>> name1="python" >>> lst1=[10,20.5,3+5j,'hello']
>>> id(num)
>>> name2=name1 >>> lst2=lst1
140708846770224
>>> lst2
>>> num1=num >>> name1 is name2
>>> num1 [10, 20.5, (3+5j), 'hello']
True
10 >>> lst2 is lst1
>>> id(num1) >>> name2
True
140708846770224 'python'
>>> num1=20 >>> lst2[2]=700
>>> id(num1) >>> name2=name2[:2]+'R'+name2[2:] >>> lst2 is lst1
140708846770544 >>> name2 True
>>> id(num)
'pyRthon' >>> lst1
140708846770224
>>> num1 >>> name2 is name1 [10, 20.5, 700, 'hello']
20 False >>> lst2
>>> num [10, 20.5, 700, 'hello']
10 >>> name1
>>> id(lst1)
>>> num1 is num 'python'
False 2192611260544
>>> num1 is not num >>> id(lst2)
True 2192611260544
Passing References
• When a function is called, the values of the arguments are copied
to the parameter variables.
• For lists and dictionaries a copy of the reference is used for the
parameter.
PROGRAM: Output:
def passingref(list2): list1 before calling method= [10, 20.5, (3+7j)]
list2.append('hello') list2= [10, 20.5, (3+7j), 'hello']
print("list2=",list2) list1 after calling method= [10, 20.5, (3+7j), 'hello']

list1=[10,20.5,3+7j]
print("list1 before calling method=",list1)
passingref(list1)
print("list1 after calling method=",list1) .
COPY and its types
• Copy operations are used to copy the contents of one variable to another
variable
• 3 types:
1.General copy
2.Shallow copy
3.Deep copy

General copy:
àUsing = operator
àSyntax: Var2=var1
àIt will copy the memory address of one variable to another variable
àExample: refer the references topic
Shallow copy
• Done by using copy( )
• Any modifications done with respect to the outer layer of the collection datatype will
not have impact on the other collections.
• But any modifications done with respect to the inner collection will have impact on
each other.[because both will be pointing to same inner collection]
 Example: >>> list2[1]=777 >>> id(list2[3])
>>> list1=[10,20.5,3+5j,[50,60]] >>> list2 1452426596544
>>> list2=list1.copy() [10, 777, (3+5j), [50, 60]] >>> id(list1[3])
>>> list2 >>> list1 1452426596544
[10, 20.5, (3+5j), [50, 60]]
[10, 20.5, (3+5j), [50, 60]]
>>> list2 is list1
>>> list2[3][1]=600
False
>>> list2
>>> id(list2)
[10, 777, (3+5j), [50, 600]]
1452457923200
>>> list1
>>> id(list1)
1452417563648 [10, 20.5, (3+5j), [50, 600]]
Deep copy
• Done by using copy.deepcopy( )
• Used to create separate copy of each and every item present in one
variable to another variable
• To use deepcopy( ) import copy module
 Example >>> list1[1]=777
>>> import copy >>> list1
>>> list1=[10,25.6,3+3j,[50,60]]
[10, 777, (3+3j), [50, 60]]
>>> list2=copy.deepcopy(list1)
>>> list2
>>> id(list2)
[10, 25.6, (3+3j), [50, 60]]
2241877842688
>>> list2[3][0]=555
>>> id(list1)
2241877841344 >>> list2
>>> list2 [10, 25.6, (3+3j), [555, 60]]
[10, 25.6, (3+3j), [50, 60]] >>> list1
>>> list1 [10, 777, (3+3j), [50, 60]]
[10, 25.6, (3+3j), [50, 60]]
Example programs on list
• Program to compute sum of all the elements in the list of numbers
• Program to compute sum of all odd and even elements in the list of
numbers
• Program to search for an element in the list using linear search method
• Program to demonstrate the concatenation of two lists
• Program to find the largest number in the list
• Program to find smallest number in the list
• Program to count odd numbers and even numbers in the list
• Program to count +ve and –ve numbers in the list
• Program to separate odd and even numbers in the given list
CHAPTER 2 : DICTIONARIES AND STRUCTURING DATA
• A dictionary is a mutable collection of many values.
• But unlike indexes for lists, indexes for dictionaries can use many different data types, not just integers.
• Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair.
• In code, a dictionary is typed with braces, { }.

• Examples:
>>> student={'regno':121,'name':'abhay','sem':5,'year':2019}
>>> student
{'regno': 121, 'name': 'abhay', 'sem': 5, 'year': 2019}
>>> len(student)
4
>>> student['regno']
121
>>> student['name']
'abhay'
>>> student['sem’]
5
>>> print("my name is" +student['name']+ "joined in the year" +str(student['year']))
my name is abhay joined in the year 2019
Dictionaries vs. Lists
• Unlike lists, items in dictionaries are unordered.
• There is no “first” item in a dictionary.
• While the order of items matters for determining whether two lists are the same,
it does not matter in what order the key-value pairs are typed in a dictionary.
>>> lsit1=list2 >>> dict1={'a':10,'b':'python','c':3+7j}

>>> list1=['cat','dog',20,30.6] >>> dict2={'b':'python','a':10,'c':3+7j}


>>> dict1==dict2
>>> list2=[30.6,'dog',20,'cat']
True
>>> list1==list2
>>> dict1 in dict2
False
Traceback (most recent call last):
>>> list1 is list2
File "<pyshell#12>", line 1, in <module>
False dict1 in dict2
>>> list1 in list2 TypeError: unhashable type: 'dict’
False >>> dict3={'b':'python','a':10,'c':3+7j,'d':30.6}
>>> dict1==dict3
False
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} Output1:
while True: Enter a name: (blank to quit)
print('Enter a name: (blank to quit)')
name = input() I do not have birthday information for
if name == '': What is their birthday?
break Enter a name: (blank to quit)
if name in birthdays: Alice
print(birthdays[name] + ' is the birthday of ' + name) Apr 1 is the birthday of Alice
else: Enter a name: (blank to quit)
print('I do not have birthday information for ' + name) Eve
print('What is their birthday?’) I do not have birthday information for Eve
bday = input() What is their birthday?
birthdays[name]=bday Dec 5
print('Birthday database updated.') Birthday database updated.
Enter a name: (blank to quit)
Eve
Dec 5 is the birthday of Eve
ORDERED DICTIONARIES IN PYTHON 3.7
>>>student={'name':'puneeth','usn':'1sj19cs021','age':21}  list(student)
>>>student ['name', 'usn', 'age']
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 21}  >>> list(student1)
['usn', 'name', 'age’]
>>>student1={'usn':'1sj19cs022','name':'raj','age': 21} lst1=list(student)
>>>student1  >>> lst1
{'usn': '1sj19cs022', 'name': 'raj', 'age': 21} ['name', 'usn', 'age']
 >>> lst1[0]
>>>student==student1
'name’
False
 student[0]
>>>student is student1
Traceback (most recent call last):
False
File "<pyshell#5>", line 1, in <module>
>>>id(student) student[0]
2920726861248 KeyError: 0
>>>id(student1)  >>> student['name']
2920726554624 'puneeth'
ADDING OF ELEMENT TO DICTIONARY
>>> student={'name':'puneeth','usn':'1sj19cs021','age':21} >>> student1
>>> student['usn'] {'name': 'pranav', 'usn': '1sj19cs035’}
'1sj19cs021' >>> student1.update({'age':25})
>>> student['marks']=35 >>> student1
>>> student {'name': 'pranav', 'usn': '1sj19cs035', 'age': 25}
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 21, 'marks': 35}
>>> student1
>>> student1={} {'name': 'pranav', 'usn': '1sj19cs035', 'age': 25}
>>> student2
>>> student1['name']='raj'
{'name': 'puneeth', 'usn': '1sj19cs035'}
>>> student1['usn','marks']='cs123',100
>>> student1
>>> student2.update(student1)
>>> student2
{'name': 'raj', ('usn', 'marks'): ('cs123', 100)}
{'name': 'pranav', 'usn': '1sj19cs035', 'age': 25}
The keys( ), values( ), and items( ) Methods
 There are three dictionary methods that will return list-like values of the dictionary’s keys, values, or
both keys and values: keys(), values(), and items().
 The values returned by these methods are not true lists: they cannot be modified and do not have
an append() method. But these data types (dict_keys, dict_values, and dict_items, respectively)
can be used in for loops.

>>> student={'name':'raj','usn':'1sj19cs034','marks':300}
>>> student
{'name': 'raj', 'usn': '1sj19cs034', 'marks': 300}
>>> list(student)
>>> student.keys()
['name', 'usn', 'marks’]
dict_keys(['name', 'usn', 'marks'])
>>>list(student.keys())
['name', 'usn', 'marks’] >>> student.values()
dict_values(['raj', '1sj19cs034', 300])
>>> student.items()
dict_items([('name', 'raj'), ('usn', '1sj19cs034'), ('marks', 300)])
Modifying values of keys

>>> student
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 21}
>>> student['age']=23
>>> student
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 23}
Aliasing and copying
• Because dictionaries are mutable, you need to be aware of aliasing.
• Whenever two variables refer to the same object, changes to one affect the other.
• If you want to modify a dictionary and keep a copy of the original, use the copy method.

>>>student student2=student1.copy()
{'name': 'puneeth', 'usn': '1sj19cs021'} >>> student2
>>> student1=student {'name': 'puneeth', 'usn': '1sj19cs035'}
>>> student >>> student1
{'name': 'puneeth', 'usn': '1sj19cs021’} {'name': 'puneeth', 'usn': '1sj19cs035’}

>>> student['usn']='1sj19cs035' student1['name']='pranav'


>>> student >>> student1
{'name': 'puneeth', 'usn': '1sj19cs035'} {'name': 'pranav', 'usn': '1sj19cs035'}
>>> student1 >>> student2
{'name': 'puneeth', 'usn': '1sj19cs035'} {'name': 'puneeth', 'usn': '1sj19cs035'}
Deleting element from dictionary
>>> student={'name':'puneeth','usn':'1sj19cs021','age':21} >>> student={'name': 'puneeth', 'usn': '1sj19cs021', 'age': 23}
>>> student >>> student.pop('usn')
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 21} '1sj19cs021'
>>> student

>>> del student['age'] {'name': 'puneeth', 'age': 23}

>>> student
>>> student
{'name': 'puneeth', 'usn': '1sj19cs021’}
{'name': 'puneeth', 'usn': '1sj19cs021', 'age': 23}
>>> student.popitem()
>>> student.popitem()
('age', 23)
('age', 23) >>> student
>>> student {'name': 'puneeth', 'usn': '1sj19cs021'}
{'name': 'puneeth', 'usn': '1sj19cs021'}
keys()
Ex1:student={'name':'raj','usn':'1sj19cs034','marks':300}
for i in student.keys():
print(i)
Output:
name
usn
marks

Ex2: student={'name':'raj','usn':'1sj19cs034','marks':300}
lst1=[]
for i in student.keys():
lst1+=[i]
print(lst1)
Output:
['name', 'usn', 'marks']
VALUES( )

>>> list(student.values())
['raj', '1sj19cs034', 300]

Ex2:
Ex1: student={'name':'raj','usn':'1sj19cs034','marks':300}
student={'name':'raj','usn':'1sj19cs034','marks':300} lst1=[]
for i in student.values(): for i in student.values():
print(i) lst1+=[i]
print(lst1)
Output:
raj Output:
1sj19cs034 ['raj', '1sj19cs034', 300]
300
items( )
>>>list(student.items())
[('name', 'raj'), ('usn', '1sj19cs034'), ('marks', 300)]

Ex:
student={'name':'raj','usn':'1sj19cs034','marks':300}
for k,v in student.items():
print('key=',k,'value=‘,v)

Output:
key= name value= raj
key= usn value= 1sj19cs034
key= marks value= 300
Checking Whether a Key or Value Exists in a Dictionary

>>>student={'name':'raj’, >>> 'raj' in student.values()


'usn':'1sj19cs034’, True
'marks':300} >>> 'appu' in student.values()
>>> 'name' in student False
True >>> 'name','raj' in student.items()
>>> 'sem' in student
('name', False)
False
>>> ('name','raj') in student.items()
>>> 'name' in student.keys()
True True
>>> 'sem' in student.keys() >>>student.items()
False dict_items([('name', 'raj'), ('usn', '1sj19cs034’),
('marks', 300)])
The get( ) Method
• get() method that takes two arguments: the key of the value to retrieve and a
fallback value to return if that key does not exist.

Example 1:
student={'name':'raj','usn':'1sj19cs034','marks':300}
print(‘my name is',student.get('name',0),'studying in',student.get('sem',0))
Output:
my name is raj studying in 0

Example 2:
student={'name':'raj','usn':'1sj19cs034','marks':300, 'sem':5}
print('my name is',student.get('name',0),'studying in',student.get('sem',0))
Output:
my name is raj studying in 5
The setdefault() Method
• You’ll often have to set a value in a dictionary for a certain key only if that key does not already
have a value.
• The setdefault() method offers a way to do this in one line of code. The first argument passed to
the method is the key to check for, and the second argument is the value to set at that key if the
key does not exist.
• If the key does exist, the setdefault() method returns the key’s value.

>>> student={'name':'raj','usn':'1sj19cs034','marks':300}
>>> student.setdefault('sem',5)
5
>>> student
{'name': 'raj', 'usn': '1sj19cs034', 'marks': 300, 'sem': 5}
>>> student.setdefault('usn','1sj19cs045')
'1sj19cs034'
Application example of setdefault( )
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)

Output:
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3,
'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
{' ': 13,
',': 1,
Pretty printing '.': 1,
'A': 1,
'I': 1,
import pprint 'a': 4,
message = 'It was a bright cold day in April, and the clocks were striking thirteen.' 'b': 1,
'c': 3,
count = {} 'd': 3,
for character in message: 'e': 5,
'g': 2,
count.setdefault(character, 0)
'h': 3,
count[character] = count[character] + 1 'i': 6,
pprint.pprint(count) 'k': 2,
'l': 3,
print(pprint.pformat(count)) 'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
CHAPTER 3: MANIPULATING STRINGS
Working with Strings: >>> str1="hi guy\'s welcome to python"
>>> str1
>>> msg='welcome to python'
"hi guy's welcome to python"
>>> msg
'welcome to python' >>> str1="hi guy\t's welcome to python"
>>> msg="welcome to python" >>> str1
>>> msg "hi guy\t's welcome to python"
'welcome to python’
>>> str1="hi guy\ts welcome to python"
>>> str1="hi guy's welcome to python" >>> str1
>>> str1 'hi guy\ts welcome to python'
"hi guy's welcome to python“
>>> print(str1)
>>> print(str1) hi guy s welcome to python
hi guy's welcome to python
>>> str1="hi guys,\n welcome to python" Escape character Prints as
>>> str1
\’ Single quote
'hi guys,\n welcome to python'
>>> print(str1) \" Double quote

hi guys, \t Tab
welcome to python
\n Newline (line break)

\\ Backslash
Raw Strings
• You can place an r before the beginning quotation mark of a string to make it a
raw string.
• A raw string completely ignores all escape characters and prints any backslash
that appears in the string.
• Raw strings are helpful if you are typing string values that contain many
b a c k s l a s h e s , s u c h a s t h e s t r i n g s u s e d fo r W i n d o w s f i l e p a t h s l i ke
r'C:\Users\Al\Desktop' or regular expressions

>>> print(r'That is Carol\'s cat.')


That is Carol\'s cat.
Multiline Strings with Triple Quotes

>>> print('''Dear Alice, >>> print("""Dear Alice,


Eve's cat has been arrested for Eve's cat has been arrested for
catnapping, cat burglary, and extortion. catnapping, cat burglary, and extortion.
Sincerely, Sincerely,
Bob'‘’) Bob""")

Dear Alice, Dear Alice,


Eve's cat has been arrested for Eve's cat has been arrested for
catnapping, cat burglary, and extortion. catnapping, cat burglary, and extortion.
Sincerely, Sincerely,
Bob Bob
The in and not in Operators with Strings
>>> str1="welcome to python" >>> 'come' not in str1
>>> str1
'welcome to python’ False
>>> 'met' not in str1
>>> print(str1)
welcome to python
True

>>> 'come' in str1


True

>>> 'me t' in str1


True
>>> 'met' in str1
False
Putting Strings Inside Other Strings
Method 1: (+) Method 2: (format specifier %s)
>>> print('your name is=%s %s and your age= %s'%(fname,lname,age))
>>> fname='raj'
your name is=raj kumar and your age= 4000
>>> lname='kumar'
>>> age=10 >>> 'your name is=%s %s and your age= %s'%(fname,lname,age)
>>> fname+lname+'your age is='+age 'your name is=raj kumar and your age= 4000’
Traceback (most recent call last):
Method 3: (f-strings)
File "<pyshell#3>", line 1, in <module>
>>> f'your name is={fname} {lname} and your age= {age}'
fname+lname+'your age is='+age 'your name is=raj kumar and your age= 4000’
TypeError: can only concatenate str
(not "int") to str >>> print(f'your name is={fname} {lname} and your age= {age}')
your name is=raj kumar and your age= 4000

>>> fname+lname+'your age is='+str(age) >>> 'your name is={fname} {lname} and your age= {age}'
'rajkumaryour age is=10' 'your name is={fname} {lname} and your age= {age}'
Useful String Methods:

1. upper( ) 2. lower( )
>>> subname='python'
>>> subname.upper() >>> sub='PYTHON'
'PYTHON’ >>> sub.lower()
'python’
>>> subname='pYtHoN'
>>> subname
>>> sub1='pYtHOn'
'pYtHoN’
>>> sub1.lower()

>>> subname.upper() 'python'


'PYTHON'
Example: count number of vowels
str1='EdUcatIon is WeAlTh'
count=0
for ch in str1:
if ch.upper() in ['A','E','I','O','U']:
count+=1
print("number of vowels in the string=",count)

Output:
number of vowels in the string= 8
isupper() and islower()
>>> s1='HELLO' >>> >>> s2='Hello’
>>> s1 >>> s2.upper().islower()
'HELLO' False
>>> s1.isupper() >>> s2.lower().isupper()
True False
>>> s1.islower() >>> s2.upper().isupper()
False True
>>> s2='Hello' >>> s2.islower().lower()
>>> s2.islower() Traceback (most recent call last):
False File "<pyshell#36>", line 1, in <module>
>>> s2.islower() s2.islower().lower()
False AttributeError: 'bool' object has no attribute 'lower'
The isX() Methods
• isalpha() Returns True if the string consists only of letters and isn’t blank

• isalnum() Returns True if the string consists only of letters and numbers and is not blank

• isdecimal() Returns True if the string consists only of numeric characters and is not blank

• isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank

• istitle() Returns True if the string consists only of words that begin with an uppercase letter followed
by only lowercase letters
Examples:
isapha() isalnum()
>>> name='python1' >>> name='python1'
>>> name.isalpha() >>> name.isalnum()
False True
>>> name='pythoN' >>> name='pythoN'
>>> name.isalpha() >>> name.isalnum()
True True
>>> name='py thON’ >>> name='py thON'
>>> name.isalpha() >>> name.isalnum()
False False
Examples:
istitle()
isdecimal() isspace() >>> title='Python'
>>> title.istitle()
>>> blank=' ' True
>>> phone='88888888'
>>> phone.isdecimal() >>> blank.isspace() >>> title1='PythON'
>>> title1.istitle()
True True False
>>> phone='888-88888' >>> tab='\t' >>> title2='Python programming'
>>> phone.isdecimal() >>> title2.istitle()
False >>> tab False
>>> title3='Python1'
>>> phone='+88 888888' '\t' >>> title3.istitle()
>>> phone.isdecimal() >>> print(tab) True
False >>> title4='5sem'
>>> phone='b78878778' >>> title4.istitle()
>>> phone.isdecimal() >>> tab.isspace() False
>>> Title4='Python Program'
False True >>> Title4.istitle()
True
startswith() and endswith()
• The startswith() and endswith() methods return True if the string value they are called on begins or
ends (respectively) with the string passed to the method; otherwise, they return False.
• These methods are useful alternatives to the == equals operator if you need to check only whether
the first or last part of the string, rather than the whole thing, is equal to another string.
Examples Examples
>>> 'python'.startswith('p') >>> name='puneeth raj'
True >>> name.startswith('puneeth')
>>> 'python'.startswith('py') True
True >>> name.endswith('raj')
>>> 'python'.endswith('n')
True
True
>>> name2='puneeth’
>>> 'python'.endswith('on')
>>> name.startswith(name2)
True
True
>>> 'python'.startswith('y')
False
>>> 'python'.endswith('o')
False
join()
• The join() method is useful when you have a list of strings that need to be joined together into a single
string value.
• The join() method is called on a string, gets passed a list of strings, and returns a string.
• The returned string is the concatenation of each string in the passed-in list.

• Examples >>> lst1


>>> lst1=['hi','welcome','to','python'] ['hi', 'welcome', 'to', 'python’]
>>> lst1.join() >>> ','.join(lst1)
Traceback (most recent call last): 'hi,welcome,to,python'
File "<pyshell#13>", line 1, in <module> >>> ' '.join(lst1)
lst1.join() 'hi welcome to python’
AttributeError: 'list' object has no attribute 'join’ >>> '*'.join(lst1)
'hi*welcome*to*python'
split()
• The split() method does the opposite of join()
>>> str1='hi welcome to python'
• It’s called on a string value and returns a list
of strings. >>> str1
• By default, the string is split wherever 'hi welcome to python'
whitespace characters such as the space, >>> str1.split('o')
tab, or newline characters are found.
['hi welc', 'me t', ' pyth', 'n’]
• Examples >>> str2='''hi guys
>>> str1=','.join(lst1) welcome to
>>> str1 programming class'''
'hi,welcome,to,python' >>> str2
>>> str1.split()
'hi guys\nwelcome to\nprogramming class'
['hi,welcome,to,python’]
>>> str2.split()
>>> str1.split(',')
['hi', 'guys', 'welcome', 'to', 'programming', 'class’]
['hi', 'welcome', 'to', 'python’]
>>> str2.split('\n')
>>> 'hi welcome to python'.split()
['hi', 'welcome', 'to', 'python'] ['hi guys', 'welcome to', 'programming class']
Splitting Strings with the partition()
• The partition() string method can split a string into the text before and after a separator string.
• This method searches the string it is called on for the separator string it is passed, and returns a
tuple of three substrings for the “before,” “separator,” and “after” substrings
• If the separator string can’t be found, the first string returned in the tuple will be the entire string,
and the other two strings will be empty.
• You can use the multiple assignment trick to assign the three returned strings to three variables.
>>> before,seperator,after=str2.partition('to')
Example: >>> before
>>> str2
'hi guys\nwelcome '
'hi guys\nwelcome to\nprogramming class'
>>> after
>>> str2.partition('\n')
'\nprogramming class'
('hi guys', '\n', 'welcome to\nprogramming class’)
>>> seperator
>>> str2.partition('welcome')
'to’
('hi guys\n', 'welcome', ' to\nprogramming class')
>>> str2.partition('python')
('hi guys\nwelcome to\nprogramming class', '', '')
Justifying Text with the rjust(), ljust(), and center() Methods
• The rjust() and ljust() string methods return a padded version of the string they
are called on, with spaces inserted to justify the text.
• The first argument to both methods is an integer length for the justified string.

Examples: >>> 'hello'.rjust(10,'*')


>>> 'hello'.rjust(10) '*****hello’
' hello' >>> 'hello'.ljust(10,'-')
>>> 'hello'.ljust(10)
'hello '
'hello-----'
>>> 'hello'.center(10) >>> 'hello'.center(10,'_')
' hello ' '__hello___'
Removing Whitespace with the strip(), rstrip(), and lstrip()
• Sometimes you may want to strip off whitespace characters (space, tab, and newline) from the
left side, right side, or both sides of a string.
• The strip() string method will return a new string without any whitespace characters at the
beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively
Examples
Examples Examples
>>> cstr
>>> lstr='hello'.ljust(10) >>> rstr='hello'.rjust(10)
' hello '
>>> lstr >>> rstr
>>> cstr.strip()
'hello ' ' hello'
'hello’
>>> lstr.strip() >>> rstr.strip()
'hello' >>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
'hello'
>>> lstr='hello'.ljust(10,'-') >>> spam.strip('ampS')
>>> rstr='hello'.rjust(10,'_')
>>> lstr >>> rstr 'BaconSpamEggs’
'hello-----' '_____hello' >>> str1
>>> lstr.strip('-') >>> rstr.strip('_') 'helloHello'
'hello' 'hello' >>> str1.strip('loH')
'helloHe'
Numeric Values of Characters with the ord() and chr() Functions

>>> ord('A')
65
>>> ord('4')
52
>>> ord('!')
33
>>> chr(65)
'A'
>>> ord('A') < ord('B')
True
>>> chr(ord('A'))
'A'
>>> chr(ord('A') + 3)
'D'
Copying and Pasting Strings with the pyperclip Module
• The pyperclip module has copy() and paste() functions that can send text to and receive text from
your computer’s clipboard.
• Sending the output of your program to the clipboard will make it easy to paste it into an email,
word processor, or some other software.

• NOTE: pyperclip module is third part module install it using the following
command in command prompt
pip install –user pyperclip
• Example
>>>import pyperclip
>>> pyperclip.copy('hello world’)
>>> stcopy=pyperclip.paste()
>>> stcopy
'hello world'

You might also like