0% found this document useful (0 votes)
11 views36 pages

Python Coding Part-3

This document provides an overview of Python lists, including their creation, indexing, slicing, and methods for adding, removing, and modifying items. It also covers list membership, reversing and sorting lists, and using list comprehensions for generating new lists. Additionally, it demonstrates how to count occurrences of items and check conditions using the all() and any() functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views36 pages

Python Coding Part-3

This document provides an overview of Python lists, including their creation, indexing, slicing, and methods for adding, removing, and modifying items. It also covers list membership, reversing and sorting lists, and using list comprehensions for generating new lists. Additionally, it demonstrates how to count occurrences of items and check conditions using the all() and any() functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python - Jupyter

Notebook

Python Coding Part-3

List
List Creation

In [423]: list1 = [] # Empty List

In [491]: print(type(list1))

<class 'list'>

In [424]: list2 = [10,30,60] # List of integers numbers

In [425]: list3 = [10.77,30.66,60.89] # List of float numbers

In [426]: list4 = ['one','two' , "three"]# List of strings

In [427]: list5 = ['Asif', 25 ,[50, 100],[150, 90]]# Nested Lists

In [428]: list6 = [100, 'Asif', 17.765] # List of mixed data types

In [429]: list7 = ['Asif', 25 ,[50, 100],[150, 90] , {'John' , 'David'}]

In [430]: len(list6) #Length of list

Out[430]: 3

List Indexing

In [432]: list2[0] # Retreive first element of the list

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'

In [435]: list4[-1] # Last item of the list

Out[435]: 'three'

In [436]: list5[-1] # Last item of the list

Out[436]: [150, 90]

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']

In [440]: mylist[:3] # Return first three items

Out[440]: ['one', 'two', 'three']

In [441]: mylist[:2] # Return first two items

Out[441]: ['one', 'two']

In [442]: mylist[-3:] # Return last three items

Out[442]: ['six', 'seven', 'eight']

In [443]: mylist[-2:] # Return last two items

Out[443]: ['seven', 'eight']

In [444]: mylist[-1] # Return last item of the list

Out[444]: 'eight'

In [445]: mylist[:] # Return whole list

Out[445]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

2/36
Python - Jupyter
Notebook

Add , Remove & Change Items

In [446]: mylist

Out[446]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [447]: [Link]('nine') # Add an item to the end of the list


mylist
Out[447]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

In [448]: [Link](9,'ten') # Add item at index location 9


mylist
Out[448]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten']

In [449]: [Link](1,'ONE') # Add item at index location 1


mylist
Out[449]: ['one',
'ONE',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten']

In [450]: [Link]('ONE') # Remove item "ONE"


mylist
Out[450]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten']

In [451]: [Link]() # Remove last item of the list


mylist
Out[451]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

In [452]: [Link](8) # Remove item at index location 8


mylist
Out[452]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [453]: del mylist[7] # Remove item at index location 7


mylist
Out[453]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven']

3/36
Python - Jupyter
Notebook

In [454]: # Change value of the string


mylist[0 = 1
]
mylist[1 = 2
]
mylist[2 = 3
]
mylist
Out[454]: [1, 2, 3, 'four', 'five', 'six', 'seven']

In [455]: [Link]() # Empty List / Delete all items in the list


mylist
Out[455]: []

In [456]: del mylist # Delete the whole list


mylist
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-456-50c7849aa2cb> in <module>
1 del mylist # Delete the whole list
----> 2 mylist

NameError: name 'mylist' is not defined

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 [460]: mylist2 = [Link]() # Create a copy of the list

In [461]: id(mylist2) # The address of mylist2 will be different from mylist


because mylis
Out[461]: 1537345955016

In [462]: mylist[0] = 1

In [463]: mylist

Out[463]: [1, 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten']

In [464]: mylist1 # mylist1 will be also impacted as it is pointing to the same


list
4/36
Python - Jupyter
Out[464]: [1, 'two', 'three', 'four', Notebook
'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

In [466]: list1 = ['one', 'two', 'three', 'four']


list2 = ['five', 'six', 'seven', 'eight']

In [467]: list3 = list1 + list2 # Join two lists by '+' operator


list3
Out[467]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [468]: [Link](list2) #Append list2 with list1


list1
Out[468]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

List Membership

In [469]: list1

Out[469]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [470]: 'one' in list1 # Check if 'one' exist in the list

Out[470]: True

In [471]: 'ten' in list1 # Check if 'ten' exist in the list

Out[471]: False

In [472]: if 'three' in list1: # Check if 'three' exist in the list


print('Three is present in the list')
else:
print('Three is not present in the list')
Three is present in the list

In [473]: if 'eleven' in list1: # Check if 'eleven' exist in the list


print('eleven is present in the list')
else:
print('eleven is not present in the list')
eleven is not present in the list

5/36
Python - Jupyter
Notebook
Reverse & Sort List

In [474]: list1

Out[474]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [475]: [Link]() # Reverse the list


list1

Out[475]: ['eight', 'seven', 'six', 'five', 'four', 'three', 'two', 'one']

In [476]: list1 = list1[::-1] # Reverse the list


list1
Out[476]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [477]: mylist3 = [9,5,2,99,12,88,34]


[Link]() # Sort list in ascending order
mylist3
Out[477]: [2, 5, 9, 12, 34, 88, 99]

In [478]: mylist3 = [9,5,2,99,12,88,34]


[Link](reverse=True) # Sort list in descending order
mylist3
Out[478]: [99, 88, 34, 12, 9, 5, 2]

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

Out[585]: [88, 65, 33, 21, 11, 98]

Loop through a list

In [481]: list1

Out[481]: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']

In [482]: for i in list1:


print(i)
on
e
tw
o
thre
e
four
five

6/36
Python - Jupyter
Notebook
six
seve
n
eigh
t

In [483]: for i in enumerate(list1):


print(i)
(0, 'one')
(1, 'two')
(2, 'three')
(3, 'four')
(4, 'five')
(5, 'six')(6, 'seven')(7, 'eight')

Count
In [485]: list10 =['one', 'two', 'three', 'four', 'one', 'one', 'two', 'three']

In [486]: [Link]('one') # Number of times item "one" occurred in the list.

Out[486]: 3

In [487]: [Link]('two') # Occurence of item 'two' in the list

Out[487]: 2

In [489]: [Link]('four') #Occurence of item 'four' in the list

Out[489]: 1

All / Any
The all() method returns:

True - If all elements in a list are true


False - If any element in a list is false

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]

In [817]: all(L1) # Will Return false as one value is false (Value 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]

In [820]: all(L2) # Returns false as one value is 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

List Comprehensions provide an elegant way to create new lists.


It consists of brackets containing an expression followed by a for clause, then zero
or more for or if clauses.

In [287]: mystring = "WELCOME"


mylist = [ i for i in mystring ] # Iterating through a string Using List
Compreh
mylist
Out[287]: ['W', 'E', 'L', 'C', 'O', 'M', 'E']

In [289]: mylist1 = [ i for i in range(40) if i % 2 == 0] # Display all even


numbers betwe
mylist1
Out[289]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36,
38]

In [290]: mylist2 = [ i for i in range(40) if i % 2 == 1] # Display all odd numbers


betwee
mylist2
Out[290]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37,
39]

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]

In [309]: # Odd even test


l1 = [print("{} is Even Number".format(i)) if i%2==0 else print("{} is
odd numbe
0 is Even Number
1 is odd number
2 is Even Number
3 is odd number
4 is Even Number
5 is odd number
6 is Even Number
7 is odd number
8 is Even Number
9 is odd number

In [315]: # Extract numbers from a string


mystr = "One 1 two 2 three 3 four 4 five 5 six
6789" numbers = [i for i in mystr if [Link]()]
numbers
Out[315]: ['1', '2', '3', '4', '5', '6', '7', '8', '9']

In [316]: # Extract letters from a string

mystr = "One 1 two 2 three 3 four 4 five 5 six


6789" numbers = [i for i in mystr if [Link]()]
numbers
Out[316]: ['O',
'n',
'e',
't',
'w',
'o',
't',
'h',
'r',
'e',
'e',
'f',
'o',
'u',
'r',
'f',
'i',
'v',
'e',
's',
'i',
'x']

10/36
3/25/202 Python - Jupyter
1 Notebook

Tuples
Tuple Creation
In [533]: tup1 = () # Empty tuple

In [534]: tup2 = (10,30,60)

In [535]: tup3 = (10.77,30.66,60.89) # tuple of float numbers

In [536]: tup4 = ('one','two' , "three")# tuple of strings

In [537]: tup5 = ('Asif', 25 ,(50, 100),(150, 90)) # Nested tuples

In [538]: tup6 = (100, 'Asif', 17.765) # Tuple of mixed data types

In [539]: tup7 = ('Asif', 25 ,[50, 100],[150, 90] , {'John' , 'David'} ,


(99,22,33))
In [540]: len(tup7) #Length of list

Out[540]: 6

Tuple Indexing

In [541]: tup2[0] # Retreive first element of the tuple

Out[541]: 10

In [542]: tup4[0] # Retreive first element of the tuple

Out[542]: 'one'

In [543]: tup4[0][0] # Nested indexing - Access the first character of the first
tuple ele
Out[543]: 'o'

In [544]: tup4[-1] # Last item of the tuple

Out[544]: 'three'

In [545]: tup5[-1] # Last item of the tuple

Out[545]: (150, 90)

11/36
3/25/202 Python - Jupyter
1 Notebook
Tuple Slicing

In [560]: mytuple = ('one' , 'two' , 'three' , 'four' , 'five' , 'six' , 'seven' ,


'eight'
In [547]: mytuple[0:3] # Return all items from 0th to 3rd index location excluding
the ite
Out[547]: ('one', 'two', 'three')

In [548]: mytuple[2:5] # List all items from 2nd to 5th index location excluding
the item
Out[548]: ('three', 'four', 'five')

In [549]: mytuple[:3] # Return first three items

Out[549]: ('one', 'two', 'three')

In [550]: mytuple[:2] # Return first two items

Out[550]: ('one', 'two')

In [551]: mytuple[-3:] # Return last three items

Out[551]: ('six', 'seven', 'eight')

In [552]: mytuple[-2:] # Return last two items

Out[552]: ('seven', 'eight')

In [553]: mytuple[-1] # Return last item of the tuple

Out[553]: 'eight'

In [554]: mytuple[:] # Return whole tuple

Out[554]: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')

Remove & Change Items

In [555]: mytuple

Out[555]: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')

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]

TypeError: 'tuple' object doesn't support item deletion

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

TypeError: 'tuple' object does not support item assignment

In [561]: del mytuple # Deleting entire tuple object is possible

Loop through a tuple

In [570]: mytuple

Out[570]: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')

In [571]: for i in mytuple:


print(i)
on
e
tw
o
thre
e
four
five
six
seve
n
eigh
t

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')

In [574]: [Link]('one') # Number of times item "one" occurred in the tuple.

13/36
3/25/202 Python - Jupyter
1 Notebook
Out[574]: 3

In [575]: [Link]('two') # Occurence of item 'two' in the tuple

Out[575]: 2

In [576]: [Link]('four') #Occurence of item 'four' in the tuple

Out[576]: 1

Tuple Membership

In [577]: mytuple

Out[577]: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')

In [578]: 'one' in mytuple # Check if 'one' exist in the list

Out[578]: True

In [579]: 'ten' in mytuple # Check if 'ten' exist in the list

Out[579]: False

In [581]: if 'three' in mytuple: # Check if 'three' exist in the list


print('Three is present in the tuple')
else:
print('Three is not present in the tuple')
Three is present in the tuple

In [583]: if 'eleven' in mytuple: # Check if 'eleven' exist in the list


print('eleven is present in the tuple')
else:
print('eleven is not present in the tuple')
eleven is not present in the tuple
Index Position

In [586]: mytuple

Out[586]: ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight')

In [587]: [Link]('one') # Index of first element equal to 'one'

Out[587]: 0

In [590]: [Link]('five') # Index of first element equal to 'five'

Out[590]: 4

In [591]: mytuple1

Out[591]: ('one', 'two', 'three', 'four', 'one', 'one', 'two', 'three')

14/36
3/25/202 Python - Jupyter
1 Notebook

In [593]: [Link]('one') # Index of first element equal to 'one'

Out[593]: 0

Sorting

In [594]: mytuple2 = (43,67,99,12,6,90,67)

In [595]: sorted(mytuple2) # Returns a new sorted list and doesn't change original
tuple
Out[595]: [6, 12, 43, 67, 67, 90, 99]

In [596]: sorted(mytuple2, reverse=True) # Sort in descending order

Out[596]: [99, 90, 67, 67, 43, 12, 6]

Sets
1) Unordered & Unindexed collection of items.

2) Set elements are unique. Duplicate elements are not allowed.

3) Set elements are immutable (cannot be changed).

4) Set itself is mutable. We can add or remove items from it.

Set Creation

In [634]: myset = {1,2,3,4,5} # Set of numbers


myset
Out[634]: {1, 2, 3, 4, 5}

In [635]: len(myset) #Length of the set

Out[635]: 5

In [636]: my_set = {1,1,2,2,3,4,5,5}


my_set # Duplicate elements are not allowed.
Out[636]: {1, 2, 3, 4, 5}

In [637]: myset1 = {1.79,2.08,3.99,4.56,5.45} # Set of float numbers


myset1
Out[637]: {1.79, 2.08, 3.99, 4.56, 5.45}

In [638]: myset2 = {'Asif' , 'John' , 'Tyrion'} # Set of Strings


myset2

15/36
3/25/202 Python - Jupyter
1 Notebook
Out[638]: {'Asif', 'John', 'Tyrion'}

In [639]: myset3 = {10,20, "Hola", (11, 22, 32)} # Mixed datatypes


myset3
Out[639]: {(11, 22, 32), 10, 20, 'Hola'}

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

TypeError: unhashable type: 'list'

In [641]: myset4 = set() # Create an empty set


print(type(myset4))
<class 'set'>

In [673]: my_set1 = set(('one' , 'two' , 'three' ,


'four')) my_set1
Out[673]: {'four', 'one', 'three', 'two'}

Loop through a Set


In [776]: myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'}

for i in myset:
print(i)
eigh
t
one
seve
n
thre
e
five
two
six
fou
r

In [777]: for i in enumerate(myset):


print(i)
(0, 'eight')
(1, 'one')
(2, 'seven')
(3, 'three')
(4, 'five')
16/36
3/25/202 Python - Jupyter
1 Notebook
(5, 'two')
(6, 'six')
(7, 'four')

Set Membership

In [675]: myset

Out[675]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}

In [676]: 'one' in myset # Check if 'one' exist in the set

Out[676]: True

In [677]: 'ten' in myset # Check if 'ten' exist in the set

Out[677]: False

In [678]: if 'three' in myset: # Check if 'three' exist in the set


print('Three is present in the set')
else:
print('Three is not present in the set')
Three is present in the set

In [679]: if 'eleven' in myset: # Check if 'eleven' exist in the list


print('eleven is present in the set')
else:
print('eleven is not present in the set')
eleven is not present in the set

Add & Remove Items

In [680]: myset

Out[680]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}

In [681]: [Link]('NINE') # Add item to a set using add() method


myset
Out[681]: {'NINE', 'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}

In [683]: [Link](['TEN' , 'ELEVEN' , 'TWELVE']) # Add multiple item to a set


using
myset
Out[683]: {'ELEVEN',
'NINE',
'TEN',
'TWELVE',
'eight',
'five',
'four',
17/36
3/25/202 Python - Jupyter
1 Notebook
'one',
'seven',
'six',
'three',
'two'}

In [684]: [Link]('NINE') # remove item in a set using remove() method


myset
Out[684]: {'ELEVEN',
'TEN',
'TWELVE',
'eight',
'five',
'four',
'one',
'seven',
'six',
'three',
'two'}

In [685]: [Link]('TEN') # remove item from a set using discard() method


myset
Out[685]: {'ELEVEN',
'TWELVE',
'eight',
'five',
'four',
'one',
'seven',
'six',
'three',
'two'}

In [688]: [Link]() # Delete all items in a set


myset
Out[688]: set()

In [689]: del myset # Delete the set object


myset
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-689-0912ea1b8932> in <module>
1 del myset
----> 2 myset

NameError: name 'myset' is not defined

Copy Set

In [705]: myset = {'one', 'two', 'three', 'four', 'five', 'six', 'seven',


'eight'} myset

18/36
3/25/202 Python - Jupyter
1 Notebook
Out[705]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}

In [706]: myset1 = myset # Create a new reference "myset1"


myset1
Out[706]: {'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 [708]: my_set = [Link]() # Create a copy of the list


my_set
Out[708]: {'eight', 'five', 'four', 'one', 'seven', 'six', 'three', 'two'}

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}

In [758]: A | B # Union of A and B (All elements from both sets. NO DUPLICATES)

Out[758]: {1, 2, 3, 4, 5, 6, 7, 8}

In [759]: [Link](B) # Union of A and B

Out[759]: {1, 2, 3, 4, 5, 6, 7, 8}

In [760]: [Link](B, C) # Union of A, B and C.

Out[760]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

In [761]: """
Updates the set calling the update() method with union of A , B & C.
19/36

For below example Set A will be updated with union of A,B


3/25/202 Python - Jupyter
1 Notebook

Out[761]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Intersection

In [762]: A = {1,2,3,4,5}
B = {4,5,6,7,8}

In [763]: A & B # Intersection of A and B (Common items in both sets)

Out[763]: {4, 5}

In [764]: [Link](B) Intersection of A and B

File "<ipython-input-764-f01b60f4d31d>", line 1


[Link](B) Intersection of A and B
^
SyntaxError: invalid syntax

In [765]: """
Updates the set calling the intersection_update() method with the
intersection o

For below example Set A will be updated with the intersection of A


& B. """
A.intersection_update(
B) A
Out[765]: {4, 5}

Difference

20/36
3/25/202 Python - Jupyter
1 Notebook
In [766]: A = {1,2,3,4,5}
B = {4,5,6,7,8}

In [767]: A - B # set of elements that are only in A but not in B

Out[767]: {1, 2, 3}

In [768]: [Link](B) # Difference of sets

Out[768]: {1, 2, 3}

In [769]: B- A # set of elements that are only in B but not in A

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

For below example Set B will be updated with the difference of B


& A. """
B.difference_update(
A) B
Out[771]: {6, 7, 8}

Symmetric Difference

In [772]: A = {1,2,3,4,5}
B = {4,5,6,7,8}

In [773]: A ^ B # Symmetric difference (Set of elements in A and B but not in both.


"EXCLU
21/36
3/25/202 Python - Jupyter
1 Notebook
Out[773]: {1, 2, 3, 6, 7, 8}

In [774]: A.symmetric_difference(B) # Symmetric difference of sets

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}

Subset , Superset & Disjoint

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 [785]: [Link](A) # Set B is said to be the subset of set A if all elements


of B are
Out[785]: True

In [786]: [Link](B) # Set A is said to be the superset of set B if all


elements of B
Out[786]: True

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

Other Builtin functions


22/36
3/25/202 Python - Jupyter
1 Notebook

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

In [947]: mydict = dict() # empty dictionary


mydict
Out[947]: {}

In [948]: mydict = {} # empty dictionary


mydict
Out[948]: {}

In [949]: mydict = {1:'one' , 2:'two' , 3:'three'} # dictionary with integer keys


mydict
Out[949]: {1: 'one', 2: 'two', 3: 'three'}

In [950]: mydict = dict({1:'one' , 2:'two' , 3:'three'}) # Create dictionary using


dict()
mydict
Out[950]: {1: 'one', 2: 'two', 3: 'three'}

24/36
3/25/202 Python - Jupyter
1 Notebook

In [951]: mydict = {'A':'one' , 'B':'two' , 'C':'three'} # dictionary with


character keys
mydict
Out[951]: {'A': 'one', 'B': 'two', 'C': 'three'}

In [318]: mydict = {1:'one' , 'A':'two' , 3:'three'} # dictionary with mixed keys


mydict
Out[318]: {1: 'one', 'A': 'two', 3: 'three'}

In [319]: [Link]() # Return Dictionary Keys using keys() method

Out[319]: dict_keys([1, 'A', 3])

In [320]: [Link]() # Return Dictionary Values using values() method

Out[320]: dict_values(['one', 'two', 'three'])

In [321]: [Link]() # Access each key-value pair within a dictionary

Out[321]: dict_items([(1, 'one'), ('A', 'two'), (3, 'three')])

In [955]: mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria']} #


dictionary with
mydict
Out[955]: {1: 'one', 2: 'two', 'A': ['asif', 'john', 'Maria']}

In [956]: mydict = {1:'one' , 2:'two' , 'A':['asif' , 'john' , 'Maria'], 'B':


('Bat' , 'ca mydict
Out[956]: {1: 'one',
2: 'two',
'A': ['asif', 'john', 'Maria'],
'B': ('Bat', 'cat', 'hat')}

In [1]: mydict = {1:'one' , 2:'two' , 'A':{'Name':'asif' , 'Age' :20}, 'B':


('Bat' , 'ca mydict
Out[1]: {1: 'one',
2: 'two',
'A': {'Name': 'asif', 'Age': 20},
'B': ('Bat', 'cat', 'hat')}

In [957]: keys = {'a' , 'b' , 'c' , 'd'}


mydict3 = [Link](keys) # Create a dictionary from a sequence of
keys
mydict3
Out[957]: {'c': None, 'd': None, 'a': None, 'b': None}

In [958]: keys = {'a' , 'b' , 'c' ,


'd'} value = 10
mydict3 = [Link](keys , value) # Create a dictionary from a
sequence of
mydict3
Out[958]: {'c': 10, 'd': 10, 'a': 10, 'b': 10}

25/36
3/25/202 Python - Jupyter
1 Notebook

In [959]: keys = {'a' , 'b' , 'c' ,


'd'} value = [10,20,30]
mydict3 = [Link](keys , value) # Create a dictionary from a
sequence of
mydict3
Out[959]: {'c': [10, 20, 30], 'd': [10, 20, 30], 'a': [10, 20, 30], 'b': [10, 20,
30]}

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

In [961]: mydict = {1:'one' , 2:'two' , 3:'three' ,


4:'four'} mydict
Out[961]: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}

In [962]: mydict[1] # Access item using key

Out[962]: 'one'

In [963]: [Link](1) # Access item using get() method

Out[963]: 'one'

In [964]: mydict1 = {'Name':'Asif' , 'ID': 74123 , 'DOB': 1991 , 'job'


:'Analyst'} mydict1
Out[964]: {'Name': 'Asif', 'ID': 74123, 'DOB': 1991, 'job': 'Analyst'}

In [965]: mydict1['Name'] # Access item using key

Out[965]: 'Asif'

In [966]: [Link]('job') # Access item using get() method

Out[966]: 'Analyst'

Add, Remove & Change Items

In [967]: mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' :


'Hilsinki'} mydict1
Out[967]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'}

26/36
3/25/202 Python - Jupyter
1 Notebook

In [968]: mydict1['DOB'] = 1992 # Changing Dictionary Items


mydict1['Address'] =
'Delhi' mydict1

Out[968]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1992, 'Address': 'Delhi'}

In [969]: dict1 = {'DOB':1995}


[Link](dict1
) mydict1
Out[969]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995, 'Address': 'Delhi'}

In [970]: mydict1['Job'] = 'Analyst' # Adding items in the dictionary


mydict1
Out[970]: {'Name': 'Asif',
'ID': 12345,
'DOB': 1995,
'Address': 'Delhi',
'Job': 'Analyst'}

In [971]: [Link]('Job') # Removing items in the dictionary using Pop method


mydict1
Out[971]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995, 'Address': 'Delhi'}

In [972]: [Link]() # A random item is removed

Out[972]: ('Address', 'Delhi')

In [973]: mydict1

Out[973]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1995}

In [974]: del[mydict1['ID']] # Removing item using del method


mydict1
Out[974]: {'Name': 'Asif', 'DOB': 1995}

In [975]: [Link]() # Delete all items of the dictionary using clear method
mydict1
Out[975]: {}

In [976]: del mydict1 # Delete the dictionary object


mydict1
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-976-da2fba4eca0f> in <module>
1 del mydict1 # Delete the dictionary object
----> 2 mydict1

NameError: name 'mydict1' is not defined

27/36
3/25/202 Python - Jupyter
1 Notebook
Copy Dictionary

In [977]: mydict = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' :


'Hilsinki'} mydict
Out[977]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Hilsinki'}

In [978]: mydict1 = mydict # Create a new reference "mydict1"

In [979]: id(mydict) , id(mydict1) # The address of both mydict & mydict1 will be
the same
Out[979]: (1537346312776, 1537346312776)

In [980]: mydict2 = [Link]() # Create a copy of the dictionary

In [981]: id(mydict2) # The address of mydict2 will be different from mydict


because mydic
Out[981]: 1537345875784

In [982]: mydict['Address'] = 'Mumbai'

In [983]: mydict

Out[983]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Mumbai'}

In [984]: mydict1 # mydict1 will be also impacted as it is pointing to the same


dictionary
Out[984]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Address': 'Mumbai'}

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'}

Loop through a Dictionary

In [986]: mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Address' :


'Hilsinki' , mydict1
Out[986]: {'Name': 'Asif',
'ID': 12345,
'DOB': 1991,
'Address': 'Hilsinki',
'Job': 'Analyst'}

In [987]: for i in mydict1:


print(i , ':' , mydict1[i]) # Key & value pair
Name : Asif
ID : 12345
DOB : 1991
Address :
Hilsinki Job :

28/36
3/25/202 Python - Jupyter
1 Notebook
Analyst

29/36
3/25/202 Python - Jupyter
1 Notebook

In [988]: for i in mydict1:


print(mydict1[i]) # Dictionary items

Asif
1234
5
1991
Hilsink
i
Analyst

Dictionary Membership

In [989]: mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Job':


'Analyst'} mydict1
Out[989]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst'}

In [990]: 'Name' in mydict1 # Test if a key is in a dictionary or not.

Out[990]: True

In [991]: 'Asif' in mydict1 # Membership test can be only done for keys.

Out[991]: False

In [992]: 'ID' in mydict1

Out[992]: True

In [993]: 'Address' in mydict1

Out[993]: False

All / Any

The all() method returns:

True - If all all keys of the dictionary are true


False - If any key of the dictionary is false

The any() function returns True if any key of the dictionary is True. If not, any() returns
False.

In [995]: mydict1 = {'Name':'Asif' , 'ID': 12345 , 'DOB': 1991 , 'Job':


'Analyst'} mydict1
Out[995]: {'Name': 'Asif', 'ID': 12345, 'DOB': 1991, 'Job': 'Analyst'}

In [996]: all(mydict1) # Will Return false as one value is false (Value 0)


30/36
3/25/202 Python - Jupyter
1 Notebook
Out[996]: True

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'}

In [999]: all(mydict1) # Returns false as one value is false

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}

In [327]: square = {i:i**2 for i in range(10)}


square
Out[327]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

In [329]: key = ['one' , 'two' , 'three' , 'four' ,


'five'] value = [1,2,3,4,5]

mydict = {k:v for (k,v) in zip(key,value)} # using dict comprehension to


create
mydict
Out[329]: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

32/36
3/25/202 Python - Jupyter
1 Notebook

In [332]: mydict1 = {'a':10 , 'b':20 , 'c':30 , 'd':40 , 'e':50}


mydict1 = {k:v/10 for (k,v) in [Link]()} # Divide all values in a
diction
mydict1
Out[332]: {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0}

In [334]: str1 = "Natural Language Processing"

mydict2 = {k:v for (k,v) in enumerate(str1)} # Store enumerated values in


a dict
mydict2
Out[334]: {0: 'N',
1: 'a',
2: 't',
3: 'u',
4: 'r',
5: 'a',
6: 'l',
7: ' ',
8: 'L',
9: 'a',
10: 'n',
11: 'g',
12: 'u',
13: 'a',
14: 'g',
15: 'e',
16: ' ',
17: 'P',
18: 'r',
19: 'o',
20: 'c',
21: 'e',
22: 's',
23: 's',
24: 'i',
25: 'n',
26: 'g'}

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'}

Word Frequency using dictionary

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']

In [63]: mylist1 = set(mylist) # Unique values in a list


mylist1 = list (mylist1)
mylist1
Out[63]: ['nine',
'one',
'eight',
'two',
'seven',
'ten',
'four',
'five',
'three',
'eleven',
'six']

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

You might also like