Python Coding Part-3
Python Coding Part-3
Notebook
List
List Creation
In [491]: print(type(list1))
<class 'list'>
Out[430]: 3
List Indexing
Out[432]: 10
1/36
Python - Jupyter
Notebookof the list
In [433]: list4[0] # Retreive first element
Out[433]: 'one'
In [434]: list4[0][0] # Nested indexing - Access the first character of the first
list ele
Out[434]: 'o'
Out[435]: 'three'
List Slicing
In [437]: mylist = ['one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' ,
'eight']
In [438]: mylist[0:3] # Return all items from 0th to 3rd index location excluding
the item
Out[438]: ['one', 'two', 'three']
In [439]: mylist[2:5] # List all items from 2nd to 5th index location excluding the
item a
Out[439]: ['three', 'four', 'five']
Out[444]: 'eight'
2/36
Python - Jupyter
Notebook
In [446]: mylist
3/36
Python - Jupyter
Notebook
Copy List
In [457]: mylist = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine'
In [458]: mylist1 = mylist # Create a new reference "mylist1"
In [459]: id(mylist) , id(mylist1) # The address of both mylist & mylist1 will be
the same
Out[459]: (1537348392776, 1537348392776)
In [462]: mylist[0] = 1
In [463]: mylist
Out[463]: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten']
In [465]: mylist2 # Copy of list won't be impacted due to changes made on the
original lis
Out[465]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten']
Join Lists
List Membership
In [469]: list1
Out[470]: True
Out[471]: False
5/36
Python - Jupyter
Notebook
Reverse & Sort List
In [474]: list1
In [584]: mylist4 =
[88,65,33,21,11,98]
sorted(mylist4 # Returns a new sorted list and doesn't change
) original l
Out[584]: [11, 21, 33, 65, 88, 98]
In [585]: mylist4
In [481]: list1
6/36
Python - Jupyter
Notebook
six
seve
n
eigh
t
Count
In [485]: list10 =['one', 'two', 'three', 'four', 'one', 'one', 'two', 'three']
Out[486]: 3
Out[487]: 2
Out[489]: 1
All / Any
The all() method returns:
The any() function returns True if any element in the list is True. If not, any()
returns False.
In [816]: L1 = [1,2,3,4,0]
Out[817]: False
In [818]: any(L1) # Will Return True as we have items in the list with True value
Out[818]: True
In [819]: L2 = [1,2,3,4,True,False]
7/36
Python - Jupyter
Notebook
Out[820]: False
In [821]: any(L2) # Will Return True as we have items in the list with True value
Out[821]: True
In [822]: L3 = [1,2,3,True]
In [823]: all(L3) # Will return True as all items in the list are True
Out[823]: True
In [824]: any(L3) # Will Return True as we have items in the list with True value
Out[824]: True
List Comprehensions
In [325]: mylist3 = [num**2 for num in range(10)] # calculate square of all numbers
betwee
mylist3
Out[325]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
8/36
Python - Jupyter
Notebook
In [317]: # Multiple whole list by 10
list1 = [2,3,4,5,6,7,8]
list1 = [i*10 for i in
list1] list1
Out[317]: [20, 30, 40, 50, 60, 70, 80]
9/36
Python - Jupyter
Notebook
In [299]: #List all numbers divisible by 3 , 9 & 12 using nested "if" with List
Comprehens
mylist4 = [i for i in range(200) if i % 3 == 0 if i % 9 == 0 if i % 12 ==
0] mylist4
Out[299]: [0, 36, 72, 108, 144, 180]
10/36
3/25/202 Python - Jupyter
1 Notebook
Tuples
Tuple Creation
In [533]: tup1 = () # Empty tuple
Out[540]: 6
Tuple Indexing
Out[541]: 10
Out[542]: 'one'
In [543]: tup4[0][0] # Nested indexing - Access the first character of the first
tuple ele
Out[543]: 'o'
Out[544]: 'three'
11/36
3/25/202 Python - Jupyter
1 Notebook
Tuple Slicing
In [548]: mytuple[2:5] # List all items from 2nd to 5th index location excluding
the item
Out[548]: ('three', 'four', 'five')
Out[553]: 'eight'
In [555]: mytuple
In [556]: del mytuple[0] # Tuples are immutable which means we can't DELETE tuple
items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-556-667a276aa503> in <module>
----> 1 del mytuple[0]
12/36
3/25/202 Python - Jupyter
1 Notebook
In [557]: mytuple[0] = 1 # Tuples are immutable which means we can't CHANGE tuple
items
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-557-4cf492702bfd> in <module>
----> 1 mytuple[0] = 1
In [570]: mytuple
In [572]: for i in
enumerate(mytuple):
print(i)
(0, 'one')
(1, 'two')
(2, 'three')
(3, 'four')
(4, 'five')
(5, 'six')
(6, 'seven')
(7, 'eight')
Count
In [573]: mytuple1 =('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three')
13/36
3/25/202 Python - Jupyter
1 Notebook
Out[574]: 3
Out[575]: 2
Out[576]: 1
Tuple Membership
In [577]: mytuple
Out[578]: True
Out[579]: False
In [586]: mytuple
Out[587]: 0
Out[590]: 4
In [591]: mytuple1
14/36
3/25/202 Python - Jupyter
1 Notebook
Out[593]: 0
Sorting
In [595]: sorted(mytuple2) # Returns a new sorted list and doesn't change original
tuple
Out[595]: [6, 12, 43, 67, 67, 90, 99]
Sets
1) Unordered & Unindexed collection of items.
Set Creation
Out[635]: 5
15/36
3/25/202 Python - Jupyter
1 Notebook
Out[638]: {'Asif', 'John', 'Tyrion'}
In [640]: myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable items
like li
myset3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-640-d23fdc3a319e> in <module>
----> 1 myset3 = {10,20, "Hola", [11, 22, 32]} # set doesn't allow mutable item s like lists
2 myset3
for i in myset:
print(i)
eigh
t
one
seve
n
thre
e
five
two
six
fou
r
Set Membership
In [675]: myset
Out[676]: True
Out[677]: False
In [680]: myset
Copy Set
18/36
3/25/202 Python - Jupyter
1 Notebook
Out[705]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}
In [707]: id(myset) , id(myset1) # The address of both myset & myset1 will be the
same as
Out[707]: (1537349033320, 1537349033320)
In [710]: id(my_set) # The address of my_set will be different from myset because
my_set i
Out[710]: 1537352902024
In [711]: [Link]('nine')
myset
Out[711]: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'}
In [712]: myset1 # myset1 will be also impacted as it is pointing to the same Set
Out[712]: {'eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two'}
In [713]: my_set # Copy of the set won't be impacted due to changes made on the
original S
Out[713]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}
Set Operation
Union
In [757]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
C = {8,9,10}
Out[758]: {1, 2, 3, 4, 5, 6, 7, 8}
Out[759]: {1, 2, 3, 4, 5, 6, 7, 8}
In [761]: """
Updates the set calling the update() method with union of A , B & C.
19/36
Intersection
In [762]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
Out[763]: {4, 5}
In [765]: """
Updates the set calling the intersection_update() method with the
intersection o
Difference
20/36
3/25/202 Python - Jupyter
1 Notebook
In [766]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
Out[767]: {1, 2, 3}
Out[768]: {1, 2, 3}
Out[769]: {6, 7, 8}
In [770]: [Link](A)
Out[770]: {6, 7, 8}
In [771]: """
Updates the set calling the difference_update() method with the
difference of se
Symmetric Difference
In [772]: A = {1,2,3,4,5}
B = {4,5,6,7,8}
Out[774]: {1, 2, 3, 6, 7, 8}
In [775]: """
Updates the set calling the symmetric_difference_update() method with the
symmet
For below example Set A will be updated with the symmetric difference of
A & B. """
A.symmetric_difference_update(
B) A
Out[775]: {1, 2, 3, 6, 7, 8}
In [784]: A = {1,2,3,4,5,6,7,8,9}
B = {3,4,5,6,7,8}
C = {10,20,30,40}
In [787]: [Link](A) # Two sets are said to be disjoint sets if they have no
common e
Out[787]: True
In [788]: [Link](A) # Two sets are said to be disjoint sets if they have no
common e
Out[788]: False
In [789]: A
Out[789]: {1, 2, 3, 4, 5, 6, 7, 8, 9}
In [790]: sum(A)
Out[790]: 45
In [791]: max(A)
Out[791]: 9
In [792]: min(A)
Out[792]: 1
In [793]: len(A)
Out[793]: 9
In [795]: list(enumerate(A))
Out[795]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
In [798]: D=
sorted(A,reverse=True)
D
Out[798]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
In [799]: sorted(D)
Out[799]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary
Dictionary is a mutable data type in Python.
A python dictionary is a collection of key and value pairs separated by a colon (:)
& enclosed in curly braces {}.
Keys must be unique in a dictionary, duplicate values are allowed.
23/36
3/25/202 Python - Jupyter
1 Notebook
Create Dictionary
24/36
3/25/202 Python - Jupyter
1 Notebook
25/36
3/25/202 Python - Jupyter
1 Notebook
In [960]: [Link](40)
mydict3
Out[960]: {'c': [10, 20, 30, 40],
'd': [10, 20, 30, 40],
'a': [10, 20, 30, 40],
'b': [10, 20, 30, 40]}
Accessing Items
Out[962]: 'one'
Out[963]: 'one'
Out[965]: 'Asif'
Out[966]: 'Analyst'
26/36
3/25/202 Python - Jupyter
1 Notebook
In [973]: mydict1
In [975]: [Link]() # Delete all items of the dictionary using clear method
mydict1
Out[975]: {}
27/36
3/25/202 Python - Jupyter
1 Notebook
Copy Dictionary
In [979]: id(mydict) , id(mydict1) # The address of both mydict & mydict1 will be
the same
Out[979]: (1537346312776, 1537346312776)
In [983]: mydict
In [985]: mydict2 # Copy of list won't be impacted due to the changes made in the
original
Out[985]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'}
28/36
3/25/202 Python - Jupyter
1 Notebook
Analyst
29/36
3/25/202 Python - Jupyter
1 Notebook
Asif
1234
5
1991
Hilsink
i
Analyst
Dictionary Membership
Out[990]: True
In [991]: 'Asif' in mydict1 # Membership test can be only done for keys.
Out[991]: False
Out[992]: True
Out[993]: False
All / Any
The any() function returns True if any key of the dictionary is True. If not, any() returns
False.
31/36
3/25/202 Python - Jupyter
1 Notebook
In [997]: any(mydict1) # Will Return True as we have items in the dictionary with
True va
Out[997]: True
In [998]: mydict1[0] =
'test1' mydict1
Out[998]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst', 0: 'test1'}
Out[999]: False
In [1000]: any(mydict1) # Will Return True as we have items in the dictionary with
True va
Out[1000]: True
Dictionary Comprehension
In [323]: double = {i:i*2 for i in range(10)} #double each value using dict
comprehension
double
Out[323]: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
32/36
3/25/202 Python - Jupyter
1 Notebook
33/36
In [337]: str1 = "abcdefghijklmnopqrstuvwxyz"
mydict3 = {i:[Link]() for i in str1} # Lower to Upper Case
mydict3
Out[337]: {'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L',
'm': 'M',
'n': 'N',
'o': 'O',
'p': 'P',
'q': 'Q',
'r': 'R',
's': 'S',
't': 'T',
'u': 'U',
'v': 'V',
'w': 'W',
'x': 'X',
'y': 'Y',
'z': 'Z'}
In [61]: mystr4 = "one two three four one two two three five five six seven six
seven one
34/36
In [64]: mylist = [Link]() # Split String into substrings
mylist
Out[64]: ['one',
'two',
'three',
'four',
'one',
'two',
'two',
'three',
'five',
'five',
'six',
'seven',
'six',
'seven',
'one',
'one',
'one',
'ten',
'eight',
'ten',
'nine',
'eleven',
'ten',
'ten',
'nine']
35/36
In [60]: # Calculate frequenct of each word
count1 = [0] * len(mylist1)
mydict5 = dict()
for i in range(len(mylist1)):
for j in range(len(mylist)):
if mylist1[i] == mylist[j]:
count1[i] += 1
mydict5[mylist1[i]] = count1[i]
print(mydict5)
{'nine': 2, 'one': 5, 'eight': 1, 'two': 3, 'seven': 2, 'ten': 4, 'four':
1, 'f
ive': 2, 'three': 2, 'eleven': 1, 'six': 2}
36/36