LISTS IN PYTHON
❖
Python lists are used to store a list of values of any type.
❖
Lists are mutable.
❖
List is represented using ‘[ ]’.
❖
Example : Empty list=[ ]
❖
[10,3.5,’keerthi’,’k’]
❖
Index of first item is 0 and the last item is n-1. Here n is
numberof items in a list.
Creating a list
❖
Lists are enclosed in squarebrackets[] and each item is separated by a comma.
Initializing a list
❖
Passingvalueinlistwhiledeclaringlistisinitializingofalist
❖
e.g.
❖
list1=[‘English',‘Hindi',1997,2000]
❖
list2=[11,22,33,44,55]
❖
list3=["a","b","c","d"]
Blank list creation
❖
Alistcanbecreatedwithoutelement
❖
List4=[]
List operations
❖
Concatenation is the process of joining list together
and as a resultnew list will be formed.
❖
‘+’ -Symbol used for concatenation operator.
❖
Integer cannot be added directly to the list.
List operations(contd…)
❖
In concatenation ,both operands must be of list type.
❖
List+ List=List
❖
List Integer=Invalid
❖
List String=Invalid
REPLICATION:
❖
“*” OPERATOR used for replicating the list according to the number
specified by the user.
❖
“*”operator requires the operands to be integer and list.
❖
List*Integer=valid
❖
List * List=Invalid
❖
String * List =Invalid
List comparison
❖
List can be compared using standard comparison operators: <,>
,<=,>=,==,!=
❖
If list contain characters ,then comparison will be done
character bycharacter based on the ASCII VALUES.
❖
The elements of list must be of comparable type(‘<‘ –
not supported between int and str)
List slicing
❖
Aslice is a subset of list
elements.
❖
Slice notation takes the form
❖
my_list[start:stop]
❖
my_list[1:5] => ['b', 'c', 'd', ‘e’]
❖
my_list[::2]
['a', 'c', 'e', 'g', 'i’]
❖
my_list[1::2]=>['b', 'd',
'f', 'h’]
❖
my_list[::-1]
❖
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a’]
Multidimensional list
Tuples in python
❖
Tuples are sequence which is used to store a elements
of differentdata type.
❖
Tuples are immutable objects.
❖
Lists uses square bracket [ ] where as tuples use parentheses.()
❖
Example:
❖
T=()
❖
(1,2,3,4)
❖
(1,’keerthi’,’4.5’)
❖
(‘a’,’b’,’c’)
Creating tuples from existing sequence
❖
Tuples in python can be created from the sequence which is passed as
argument
❖
Example: tuple(‘keerthi’,’arun’)
❖
tuple(‘keerthi’)
❖
Tuple([‘keerthi’,20,4.5])
❖
eval()
❖
Tuple() function will create individual characters as elements.
❖
Eval () can be used to overcome this issue.
Example: t=eval(input(“enter the elements for a tuple:”))
print(t)
Accessing Values from Tuples/tuple slicing
❖
Use the square brackets for slicing along with the index or indices to obtain the value available at that index.
❖
e.g.
❖
tup1 = ("comp sc", "info practices", 2017, 2018) tup2 = (5,11,22,44,9,66)
❖
print ("tup1[0]: ", tup1[0])
❖
print ("tup2[1:5]: ", tup2[1:5])
❖
Output
❖
('tup1[0]: ', 'comp sc')
❖
('tup2[1:5]: ', (11, 22, 44, 9))
Iterating Through A Tuple
❖
Element of the tuple can be accessed sequentially using for loop.
❖
Syntax: for <item> in<tuple>:
❖
print(tuplename[item])
❖
tup = (5,11,22)
❖
for i in range(0,len(tup)):
print(tup[i])
❖
Output
❖ 5
❖
11
❖
22
Similarity b/w strings, list and tuple
❖
len()
❖
Indexing and Slicing
❖
Membership Operators
❖
Concatenation and replication operator
❖
Tuples can be compared using comparison (or) relational
operators.
❖
<,>,<=,>=,==,!=
❖
Example:
❖
T=(10,20,30)
❖
T1=(40,50,60)
Relational operators(or)
comparison operators.
Comparison in tuple can be made only if the elements are of
comparable type.
Tuple operations
❖
Concatenation Operator:
❖
‘+’ operator is used for combining tuples .
❖
Both the operands must be of type
tuple. ❖
Example: (10,20,30,40)+(50,)
❖
Tuple+ Tuple=valid
❖
Tuple+integer=Invalid
❖
String+tuple=Invalid
Tuple operations
❖
Replication Operator:
❖
‘*’ operator is used for replication
❖
Example: T=(20,’keerthi’,60.5)
❖
T*3
Tuple*integer=vali
d
Tuple*Tuple=Invali
d
String*tuple=Invali
d
Delete Tuple Elements
✓
Direct deletion of tuple element is not possible butshifting of
required content after discard of unwanted content to another tuple. e.g.
✓
tup1 = (1, 2,3)
✓
tup3 = tup1[0:1] + tup1[2:] print (tup3)
Packing and unpacking in tuple:
❖
Forming a tuple form individual elements is called packing.
❖
Creating individual values from tuple’s element is called Unpacking.
❖
T=(20,80,100) -------->packing
❖
X,Y,Z=T -----> Unpacking
Tuple methods:
Tuple methods:
count()- method returns the number of times a specified value appears in the tuple.
t = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5,5)
x = t.count(5)
print(x)
OUTPUT->3
index()– returns the index position of first occurrence of a value in tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'u’)
i = vowels.index('e’)
print('The index of e:', i)
OUTPUT ->1
Tuple methods:
sum()- sum of tuple elements can be done via list
x = (1,4,6)
r= sum(list(x))
print('sum of elements in tuple', r)
OUTPUT->11
sorted()- returns the sorted elements list
x = (1,4,6)
r= sorted(x)
print(sorted elements in tuple', r)
Tuple methods:
max of a tuple elements.
x = (1,4,6)
r= max(x)
print('maximum value in tuple', r)
OUTPUT->6
mean/average of a tuple elements.
x = (1,4,6)
r= sum(x)/len(x) print(mean of tuple is ', r)
OUTPUT->3.66
DICTIONARY
❖
It is an unordered collection of items where each item consist of a key and
a value.
❖
It is mutable (can modify its contents ) but Key must be unique and immutable.
Creating A Dictionary
❖
It is enclosed in curly braces {} and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon (:).Passing value in
dictionary at declaration is dictionary initialization.get() method is used to access value
of a key
❖
e.g.
❖
dict = {‘Subject’: ‘COMPUTER SCIENCE', 'Class': ‘12'}
❖
Accessing List Item
❖
dict = {‘Subject’: ‘COMPUTER SCIENCE', 'Class': ‘12'}
❖
print(dict)
❖
print ("Subject : ", dict['Subject'])
❖
print ("Class : ", dict.get('Class'))
❖
OUTPUT
❖
{'Class': '11', 'Subject': 'Informatics Practices'}
❖
('Subject : ', 'Informatics Practices’)
❖
('Class : ', 11)
❖
Deleting dictionary elements
del, pop() and clear() statement are used to remove elements from the dictionary.
Del e.G.
Dict = {'subject': 'informatics practices', 'class': 11}
print('before del', dict)
del dict['class'] # delete single element print('after item delete', dict)
del dict #delete whole dictionary print('after dictionary delete', dict)
output
('before del', {'class': 11, 'subject': 'informatics practices'})
('after item delete', {'subject': 'informatics practices’})
('after dictionary delete', <type 'dict'>)
e.g.
dict = {'Subject': ‘Cs', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)
Output
('before del', {'Class': 11, 'Subject': ‘Cs'})
('after item delete', {'Subject': ‘Cs’})
('after clear', {})
Built-in Dictionary Functions
S.No. Function & Description
len(dict)Gives the total length of the dictionary. It is equal to
the number of items in the dictionary.
1 dict = {'Name': 'Aman', 'Age': 37};
print ("Length : %d" % len (dict))
OUTPUT ->2
2
str(dict)Return a printable string representation of a
dictionary
type(variable)If variable is dictionary, then it would return a
3
dictionary type.
Built-in Dictionary Methods
S.No. Method & Description
dict() - creates dictionary
1 x = dict(name = “Aman", age = 37, country = “India")
Here x is created as dictionary
keys() - returns all the available keys
2
x = dict(name = “Aman", age = 37, country = “India")
print(x.keys())
OUTPUT->dict_keys(['country', 'age', 'name'])
values() - returns all the available values
3
x = dict(name = “Aman", age = 37, country = “India")
print(x.values())
OUTPUT->dict_values(['India', 37, 'Aman'])
Built-in Dictionary Methods
S.No. Method & Description
items() - return the list with all dictionary keys with values.
4
x = dict(name = "Aman", age = 37, country = "India")
print(x.items())
OUTPUT->dict_items([('country', 'India'), ('age', 37), ('name', 'Aman')])
update()-used to change the values of a key and add new keys
x = dict(name = "Aman", age = 37, country = "India")
5
d1 = dict(age= 39)
x.update(d1,state="Rajasthan")
print(x)
OUTPUT-{'country': 'India', 'age': 39,'name':'Aman','state': 'Rajasthan'}
Built-in Dictionary Methods
Built-in Dictionary Methods
S.No. Method & Description
copy() - returns a shallow copy of the dictionary.
x = dict(name = "Aman", age = 37, country = "India")
y=x.copy()
print(y)
8 print(id(x))
print(id(y))
OUTPUT - >{'country': 'India', 'age': 37, 'name':
'Aman'} 33047872 33047440
popitem() – removes last item from dictionary
x = dict(name = "Aman", age = 37, country = "India")
9 x.popitem()
print(x)
OUTPUT-> {'age': 37, 'name': 'Aman'}
Built-in Dictionary Methods
S.No. Method & Description
setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value.
10
x = dict(name = "Aman", country = "India")
y=x.setdefault('age',39)
print(y)
OUTPUT-> 39
max() – returns key having maximum value
Tv = {'a':100, 'b':1292, 'c' : 88}
11 Keymax = max(Tv, key=Tv.get)
print(Keymax)
OUTPUT-> b
12 min()- returns key having minimum value
Built-in Dictionary Methods
S.No. Method & Description
sorted- sort by key or value
dict1 = {'b':100, 'a':12, 'c' : 88}
y = sorted(dict1.items())
print(y)
OUTPUT-> [('b', 100), ('c', 88), ('a', 12)]

Revision Tour 1 and 2 complete.doc

  • 1.
    LISTS IN PYTHON ❖ Pythonlists are used to store a list of values of any type. ❖ Lists are mutable. ❖ List is represented using ‘[ ]’. ❖ Example : Empty list=[ ] ❖ [10,3.5,’keerthi’,’k’] ❖ Index of first item is 0 and the last item is n-1. Here n is numberof items in a list.
  • 2.
    Creating a list ❖ Listsare enclosed in squarebrackets[] and each item is separated by a comma. Initializing a list ❖ Passingvalueinlistwhiledeclaringlistisinitializingofalist ❖ e.g. ❖ list1=[‘English',‘Hindi',1997,2000] ❖ list2=[11,22,33,44,55] ❖ list3=["a","b","c","d"] Blank list creation ❖ Alistcanbecreatedwithoutelement ❖ List4=[]
  • 5.
    List operations ❖ Concatenation isthe process of joining list together and as a resultnew list will be formed. ❖ ‘+’ -Symbol used for concatenation operator. ❖ Integer cannot be added directly to the list.
  • 6.
    List operations(contd…) ❖ In concatenation,both operands must be of list type. ❖ List+ List=List ❖ List Integer=Invalid ❖ List String=Invalid REPLICATION: ❖ “*” OPERATOR used for replicating the list according to the number specified by the user. ❖ “*”operator requires the operands to be integer and list. ❖ List*Integer=valid ❖ List * List=Invalid ❖ String * List =Invalid
  • 7.
    List comparison ❖ List canbe compared using standard comparison operators: <,> ,<=,>=,==,!= ❖ If list contain characters ,then comparison will be done character bycharacter based on the ASCII VALUES. ❖ The elements of list must be of comparable type(‘<‘ – not supported between int and str)
  • 8.
    List slicing ❖ Aslice isa subset of list elements. ❖ Slice notation takes the form ❖ my_list[start:stop] ❖ my_list[1:5] => ['b', 'c', 'd', ‘e’] ❖ my_list[::2] ['a', 'c', 'e', 'g', 'i’] ❖ my_list[1::2]=>['b', 'd', 'f', 'h’] ❖ my_list[::-1] ❖ ['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a’]
  • 11.
  • 14.
    Tuples in python ❖ Tuplesare sequence which is used to store a elements of differentdata type. ❖ Tuples are immutable objects. ❖ Lists uses square bracket [ ] where as tuples use parentheses.() ❖ Example: ❖ T=() ❖ (1,2,3,4) ❖ (1,’keerthi’,’4.5’) ❖ (‘a’,’b’,’c’)
  • 15.
    Creating tuples fromexisting sequence ❖ Tuples in python can be created from the sequence which is passed as argument ❖ Example: tuple(‘keerthi’,’arun’) ❖ tuple(‘keerthi’) ❖ Tuple([‘keerthi’,20,4.5]) ❖ eval() ❖ Tuple() function will create individual characters as elements. ❖ Eval () can be used to overcome this issue. Example: t=eval(input(“enter the elements for a tuple:”)) print(t)
  • 16.
    Accessing Values fromTuples/tuple slicing ❖ Use the square brackets for slicing along with the index or indices to obtain the value available at that index. ❖ e.g. ❖ tup1 = ("comp sc", "info practices", 2017, 2018) tup2 = (5,11,22,44,9,66) ❖ print ("tup1[0]: ", tup1[0]) ❖ print ("tup2[1:5]: ", tup2[1:5]) ❖ Output ❖ ('tup1[0]: ', 'comp sc')
  • 17.
  • 18.
    Iterating Through ATuple ❖ Element of the tuple can be accessed sequentially using for loop. ❖ Syntax: for <item> in<tuple>: ❖ print(tuplename[item]) ❖ tup = (5,11,22) ❖ for i in range(0,len(tup)): print(tup[i]) ❖ Output ❖ 5 ❖ 11
  • 19.
  • 20.
    Similarity b/w strings,list and tuple ❖ len() ❖ Indexing and Slicing ❖ Membership Operators ❖ Concatenation and replication operator
  • 21.
    ❖ Tuples can becompared using comparison (or) relational operators. ❖ <,>,<=,>=,==,!= ❖ Example: ❖ T=(10,20,30) ❖ T1=(40,50,60) Relational operators(or) comparison operators. Comparison in tuple can be made only if the elements are of comparable type.
  • 22.
    Tuple operations ❖ Concatenation Operator: ❖ ‘+’operator is used for combining tuples . ❖ Both the operands must be of type tuple. ❖ Example: (10,20,30,40)+(50,) ❖ Tuple+ Tuple=valid ❖ Tuple+integer=Invalid ❖ String+tuple=Invalid
  • 23.
    Tuple operations ❖ Replication Operator: ❖ ‘*’operator is used for replication ❖ Example: T=(20,’keerthi’,60.5) ❖ T*3 Tuple*integer=vali d Tuple*Tuple=Invali d String*tuple=Invali d
  • 24.
    Delete Tuple Elements ✓ Directdeletion of tuple element is not possible butshifting of required content after discard of unwanted content to another tuple. e.g. ✓ tup1 = (1, 2,3) ✓ tup3 = tup1[0:1] + tup1[2:] print (tup3)
  • 25.
    Packing and unpackingin tuple: ❖ Forming a tuple form individual elements is called packing. ❖ Creating individual values from tuple’s element is called Unpacking. ❖ T=(20,80,100) -------->packing ❖ X,Y,Z=T -----> Unpacking
  • 26.
  • 27.
    Tuple methods: count()- methodreturns the number of times a specified value appears in the tuple. t = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5,5) x = t.count(5) print(x) OUTPUT->3 index()– returns the index position of first occurrence of a value in tuple vowels = ('a', 'e', 'i', 'o', 'i', 'u’) i = vowels.index('e’) print('The index of e:', i) OUTPUT ->1
  • 28.
    Tuple methods: sum()- sumof tuple elements can be done via list x = (1,4,6) r= sum(list(x)) print('sum of elements in tuple', r) OUTPUT->11 sorted()- returns the sorted elements list x = (1,4,6) r= sorted(x) print(sorted elements in tuple', r)
  • 29.
    Tuple methods: max ofa tuple elements. x = (1,4,6) r= max(x) print('maximum value in tuple', r) OUTPUT->6 mean/average of a tuple elements. x = (1,4,6) r= sum(x)/len(x) print(mean of tuple is ', r) OUTPUT->3.66
  • 30.
    DICTIONARY ❖ It is anunordered collection of items where each item consist of a key and a value. ❖ It is mutable (can modify its contents ) but Key must be unique and immutable.
  • 31.
    Creating A Dictionary ❖ Itis enclosed in curly braces {} and each item is separated from other item by a comma(,). Within each item, key and value are separated by a colon (:).Passing value in dictionary at declaration is dictionary initialization.get() method is used to access value of a key ❖ e.g. ❖ dict = {‘Subject’: ‘COMPUTER SCIENCE', 'Class': ‘12'} ❖ Accessing List Item ❖ dict = {‘Subject’: ‘COMPUTER SCIENCE', 'Class': ‘12'} ❖ print(dict) ❖ print ("Subject : ", dict['Subject']) ❖ print ("Class : ", dict.get('Class')) ❖ OUTPUT ❖ {'Class': '11', 'Subject': 'Informatics Practices'}
  • 32.
    ❖ ('Subject : ','Informatics Practices’) ❖ ('Class : ', 11)
  • 34.
    ❖ Deleting dictionary elements del,pop() and clear() statement are used to remove elements from the dictionary. Del e.G. Dict = {'subject': 'informatics practices', 'class': 11} print('before del', dict) del dict['class'] # delete single element print('after item delete', dict) del dict #delete whole dictionary print('after dictionary delete', dict) output ('before del', {'class': 11, 'subject': 'informatics practices'}) ('after item delete', {'subject': 'informatics practices’}) ('after dictionary delete', <type 'dict'>)
  • 35.
    e.g. dict = {'Subject':‘Cs', 'Class': 11} print('before del', dict) dict.pop('Class') print('after item delete', dict) dict.clear() print('after clear', dict) Output ('before del', {'Class': 11, 'Subject': ‘Cs'}) ('after item delete', {'Subject': ‘Cs’}) ('after clear', {})
  • 36.
    Built-in Dictionary Functions S.No.Function & Description len(dict)Gives the total length of the dictionary. It is equal to the number of items in the dictionary. 1 dict = {'Name': 'Aman', 'Age': 37}; print ("Length : %d" % len (dict)) OUTPUT ->2 2 str(dict)Return a printable string representation of a dictionary type(variable)If variable is dictionary, then it would return a 3 dictionary type.
  • 37.
    Built-in Dictionary Methods S.No.Method & Description dict() - creates dictionary 1 x = dict(name = “Aman", age = 37, country = “India") Here x is created as dictionary keys() - returns all the available keys 2 x = dict(name = “Aman", age = 37, country = “India") print(x.keys()) OUTPUT->dict_keys(['country', 'age', 'name']) values() - returns all the available values 3 x = dict(name = “Aman", age = 37, country = “India") print(x.values()) OUTPUT->dict_values(['India', 37, 'Aman'])
  • 38.
    Built-in Dictionary Methods S.No.Method & Description items() - return the list with all dictionary keys with values. 4 x = dict(name = "Aman", age = 37, country = "India") print(x.items()) OUTPUT->dict_items([('country', 'India'), ('age', 37), ('name', 'Aman')]) update()-used to change the values of a key and add new keys x = dict(name = "Aman", age = 37, country = "India") 5 d1 = dict(age= 39) x.update(d1,state="Rajasthan") print(x) OUTPUT-{'country': 'India', 'age': 39,'name':'Aman','state': 'Rajasthan'}
  • 39.
  • 40.
    Built-in Dictionary Methods S.No.Method & Description copy() - returns a shallow copy of the dictionary. x = dict(name = "Aman", age = 37, country = "India") y=x.copy() print(y) 8 print(id(x)) print(id(y)) OUTPUT - >{'country': 'India', 'age': 37, 'name': 'Aman'} 33047872 33047440 popitem() – removes last item from dictionary x = dict(name = "Aman", age = 37, country = "India") 9 x.popitem() print(x) OUTPUT-> {'age': 37, 'name': 'Aman'}
  • 41.
    Built-in Dictionary Methods S.No.Method & Description setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value. 10 x = dict(name = "Aman", country = "India") y=x.setdefault('age',39) print(y) OUTPUT-> 39 max() – returns key having maximum value Tv = {'a':100, 'b':1292, 'c' : 88} 11 Keymax = max(Tv, key=Tv.get) print(Keymax) OUTPUT-> b 12 min()- returns key having minimum value
  • 42.
    Built-in Dictionary Methods S.No.Method & Description sorted- sort by key or value dict1 = {'b':100, 'a':12, 'c' : 88} y = sorted(dict1.items()) print(y) OUTPUT-> [('b', 100), ('c', 88), ('a', 12)]