Module 2 Ppt
Module 2 Ppt
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,
• 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']
>>> 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=[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>
>>> 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
• 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.
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()
if animal==petanimal:
flag=True
break
if flag==True:
else:
20 >>> d
5j
>>> z >>> a,b,c,d,e=list1
>>> 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']
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}
>>> 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
>>> 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
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
>>> 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()
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.
>>> 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'