Notes Again Harry
Notes Again Harry
CHARACTER
Data Type
Variable
Variable is like a container that holds data. Very similar to how our containers in
kitchen holds sugar,
salt etc Creating a variable is like creating a placeholder in memory and
assigning it some
value. In Python its as easy as writing:
What is Data
type
types
3. Boolean data:
Boolean data consists of values True or False.
4. Sequenced data: list, tuple
list: A list is an ordered collection of data with elements separated by a comma
and enclosed within square brackets. Lists are mutable and can be modified after
creation.
Type casting
The conversion of one data type into the other data type is known as type casting
in python or type conversion in python.
Python supports a wide variety of functions or methods like: int(), float(), str(),
ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the type casting in
python.
Types of Typecasting
Explicit conversion
The conversion of one data type into another data type, done via developer or
programmer's intervention or manually as per the requirement, is known as explicit
type conversion.
It can be achieved with the help of Python’s built-in type conversion functions
such as int(), float(), hex(), oct(), str(), etc .
for example
string = "15"
number = 7
string_number = int(string) #throws an error if the string is not a valid integer
sum= number + string_number
print("The Sum of both the numbers is: ", sum)
Implicit Conversion
Data types in Python do not have the same level i.e. ordering of data types is not
the same in Python. Some of the data types have higher-order,
and some have lower order. While performing any operations on variables with
different data types in Python,
one of the variable's data types will be changed to the higher data type.
According to the level,
one data type is converted into other by the Python interpreter itself
(automatically). This is called, implicit typecasting in python.
Python converts a smaller data type to a higher data type to prevent data loss.
for Example
# Python automatically converts
# a to int
a = 7
print(type(a))
ABOUT Strings?
In python, anything that you enclose between single or double quotation marks is
considered a string.
A string is essentially a sequence or array of textual data. Strings are used when
working with Unicode characters.
OUTPUT
Hello, Faisal
Note: It does not matter whether you enclose your strings in single or double
quotes, the output remains the same.
Sometimes, the user might need to put quotation marks in between the strings.
Example, consider the sentence: He said, “I want to eat an apple”.
How will you print this statement in python?: He said, "I want to eat an apple". We
will definitely use single quotes for our convenience
Multiline Strings..
print(name[0])
print(name[1])
String slicingsss
String is an Array
Example:
pie = "ApplePie"
print(pie[:5])
print(pie[6]) #returns character at specified index
Slicing Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E
String methods
Python provides a set of built-in methods that we can use to alter and modify the
strings.
upper() :
The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print(str1.upper())
Output:
ABCDEFGHIJ
lower()
Example:
str1 = "AbcDEfghIJ"
print(str1.lower())
Output:
abcdefghij
strip() :
The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print(str2.strip)
Output:
Silver Spoon
rstrip() :
the rstrip() removes any trailing characters. Example:
replace() :
The replace() method replaces all occurences of a string with another string.
Example:
split() :
The split() method splits the given string at the specified instance and returns
the separated strings as list items.
Example:
str2 = "Silver Spoon"
print(str2.split(" ")) #Splits the string at the whitespace " ".
Output:
['Silver', 'Spoon']
There are various other string methods that we can use to modify our strings.
capitalize() :
The capitalize() method turns only the first character of the string to uppercase
and the rest other characters of the string are turned to lowercase. The string
has no effect if the first character is already uppercase.
Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)
Output:
Hello
Hello world
center() :
The center() method aligns the string to the center as per the parameters given by
the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50))
Output:
Welcome to the Console!!!
We can also provide padding character. It will fill the rest of the fill characters
provided by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))
Output:
............Welcome to the Console!!!.............
count() :
The count() method returns the number of times the given value has occurred within
the given string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
Output:
4
endswith() :
The endswith() method checks if the string ends with a given value. If yes then
return True, else return False.
Example :
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
Output:
True
We can even also check for a value in-between the string by providing start and end
index positions.
Example:
str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))
Output:
True
find() :
The find() method searches for the first occurrence of the given value and returns
the index where it is present.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))
Output:
10
As we can see, this method is somewhat similar to the index() method. The major
difference being that index() raises an exception if value is absent whereas find()
does not.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value and returns
the index where it is present. If given value is absent from the string then raise
an exception.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The major
difference being that index() raises an exception if value is absent whereas find()
does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
Output:
ValueError: substring not found
isalnum() :
The isalnum() method returns True only if the entire string only consists of A-Z,
a-z, 0-9.
If any other characters or punctuations are present, then it returns False.
Example 1:
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of A-Z,
a-z.
If any other characters or punctuations or numbers(0-9) are present, then it
returns False.
Example :
str1 = "Welcome"
print(str1.isalpha())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are lower
case, else it returns False.
Example:
str1 = "hello world"
print(str1.islower())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given string are
printable, if not, then return False.
Example :
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains white
spaces, else returns False.
Example:
str1 = " " #using Spacebar
print(str1.isspace())
str2 = " " #using Tab
print(str2.isspace())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example:
str1 = "World Health Organization"
print(str1.istitle())
Output:
True
Example:
str2 = "To kill a Mocking bird"
print(str2.istitle())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are upper
case, else it returns False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
Output:
True
startswith() :
The endswith() method checks if the string starts with a given value. If yes then
return True, else return False.
Example :
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper case are
converted to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print(str1.swapcase())
Output:
pYTHON IS A iNTERPRETED lANGUAGE
title() :
The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())
Output:
He'S Name Is Dan. Dan Is An Honest Man.
if-else Statements
Sometimes the programmer needs to check the evaluation of certain expression(s),
whether the expression(s) evaluate to True or False. If the expression evaluates to
False, then the program execution follows a different path than it would have if
the expression had evaluated to True.
Based on this, the conditional statements are further classified into following
types:
if
if-
else
if-
else-elif
nested
if-else-elif.
An if……else statement evaluates like this:
if the expression evaluates True:
Execute the block of code inside if statement. After execution return to the code
out of the if……else block.\
Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1 kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")
Output:
Alexa, do not add Apples to the cart.
elif
Statements
Sometimes, the programmer may want to evaluate more than one condition, this can be
done using an elif statement.
Execute the block of code inside the first elif statement if the expression inside
it evaluates True. After execution return to the code out of the if block.
Execute the block of code inside the second elif statement if the expression inside
it evaluates True. After execution return to the code out of the if block.
.
.
.
Execute the block of code inside the nth elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
Execute the block of code inside else statement if none of the expression evaluates
to True. After execution return to the code out of the if block.
Example:
num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested
if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")
Output:
A match statement will compare a given variable’s value to different shapes, also
referred to as the pattern. The main idea is to keep on comparing the variable with
all the present patterns until it fits into one.
Syntax:
match variable_name:
case ‘pattern1’ : //statement1
case ‘pattern2’ : //statement2
…
case ‘pattern n’ : //statement n
Example:
x = 4
# x is the variable to match
match x:
# if x is 0
case 0:
print("x is zero")
# case with if-condition
case 4 if x % 2 == 0:
print("x % 2 == 0 and case is 4")
# Empty case with if-condition
case _ if x < 10:
print("x is < 10")
# default case(will only be matched if the above cases were not matched)
# so it is basically just an else:
case _:
print(x)
Output:
x % 2 == 0 and case is 4
Introduction to Loops
Sometimes a programmer wants to execute a group of statements a certain number of
times. This can be done using loops. Based on this loops are further classified
into following main types;
for loop
while loop
The for Loop
for loops can iterate over a sequence of iterable objects in python. Iterating over
a sequence is nothing but iterating over strings, lists, tuples, sets and
dictionaries.
range():
What if we do not want to iterate over a sequence? What if we want to use for loop
for a specific number of times?
Example:
for k in range(5):
print(k)
Output:
0
1
2
3
4
Here, we can see that the loop starts from 0 by default and increments at each
iteration.
Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8
break statement
The break statement enables a program to skip over a part of the code. A break
statement terminates the very loop it lies within.
example
for i in range(1,101,1):
print(i ,end=" ")
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
.
.
.
50 Mississippi
Continue Statement
The continue statement skips the rest of the loop statements and causes the next
iteration to occur.
example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
output
2
4
6
8
0
\
Python Lists
*Lists are ordered collection of data items.
*They store multiple items in a single variable.
*List items are separated by commas and enclosed within square brackets [].
*Lists are changeable meaning we can alter them after creation.
Example 1:
lst1 = [1,2,2,3,5,4,6]
lst2 = ["Red", "Green", "Blue"]
print(lst1)
print(lst2)
Output:
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']
Example 2:
List Index
Each item/element in a list has its own unique index. This index can be used to
access any particular item from the list. The first item has index [0], second item
has index [1], third item has index [2] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
Accessing
list items
We can access list items by using its index with the square bracket syntax []. For
example colors[0] will give "Red", colors[1] will give "Green" and so on...
Positive Indexing:
As we have seen that list items have index, as such we can access items using these
indexes.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
print(colors[4])
print(colors[0])
Output:
Blue
Green
Red
Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but
from the end of the list. The last item has index [-1], second last item has index
[-2], third last item has index [-3] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [-5] [-4] [-3] [-2] [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])
Output:
Green
Blue
Red
Check whether an item in present in the list?
We can check if a given item is present in the list. This is done using the in
keyword.
Syntax:
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
Output:
['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']
When no end index is provided, the interpreter prints all the values till the end.
List Comprehension
List comprehensions are used for creating new lists from other iterables like
lists, tuples, dictionaries, sets, and even in arrays and strings.
Syntax:
List = [Expression(item) for item in iterable if Condition]
Iterable: It can be list, tuples, dictionaries, sets, and even in arrays and
strings.
Condition: Condition checks if the item should be added to the new list or not.
Example 1: Accepts items with the small letter “o” in the new list
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)
Output:
['Milo', 'Bruno', 'Rosa']
Example 2: Accepts items which have more than 4 letters
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if (len(item) > 4)]
print(namesWith_O)
Output:
['Sarah', 'Bruno', 'Anastasia']
List Methods
list.sort()
This method sorts the list in ascending order. The original list is updated
Example 1:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)
Output:
['blue', 'green', 'indigo', 'voilet']\
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
What if you want to print the list in descending order?
We must give reverse=True as a parameter in the sort method.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort(reverse=True)
print(num)
Output:
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]
The reverse parameter is set to False by default.
Note: Do not mistake the reverse parameter with the reverse method.
reverse()
This method reverses the order of the list.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.reverse()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.reverse()
print(num)
Output:
['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]
index()
This method returns the index of the first occurrence of the list item.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.index("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))
Output:
1
3
count()
Returns the count of the number of items with the given value.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
Output:
2
3
copy()
Returns copy of the list. This can be done to perform operations on the list
without modifying the original list.
Example:
colors = ["voilet", "green", "indigo", "blue"]
newlist = colors.copy()
print(colors)
print(newlist)
Output:
['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']
append():
This method appends items to the end of the existing list.
Example:
colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
Output:
['voilet', 'indigo', 'blue', 'green']
insert():
This method inserts an item at the given index. User has to specify index and the
item to be inserted within the insert() method.
Example:
colors = ["voilet", "indigo", "blue"]
# [0] [1] [2]
colors.insert(1, "green") #inserts item at index 1
# updated list: colors = ["voilet", "green", "indigo", "blue"]
# indexs [0] [1] [2] [3]
print(colors)
Output:
['voilet', 'green', 'indigo', 'blue']
extend():
This method adds an entire list or any other collection datatype (set, tuple,
dictionary) to the existing list.
Example 1:
#add a list to a list
colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Concatenating two lists:
You can simply concatenate two lists to join two lists.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Python
Tuples
Tuples are ordered collection of data items. They store multiple items in a single
variable. Tuple items are separated by commas
and enclosed within round brackets (). Tuples are unchangeable meaning we can not
alter them after creation.
Example 1:
tuple1 = (1,2,2,3,5,4,6)
tuple2 = ("Red", "Green", "Blue")
print(tuple1)
print(tuple2)
Output:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')
Tuple
Indexes
Each item/element in a tuple has its own unique index.
This index can be used to access any particular item from the tuple. The first
item has index [0],
second item has index [1], third item has index [2] and so on.
Example:
country = ("Spain", "Italy", "India",)
# [0] [1] [2]
Accessing tuple items:
I. Positive Indexing:
As we have seen that tuple items have index, as such we can access items using
these indexes.
Example:
Spain
Italy
India
II. Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but
from the end of the tuple. The last item has index [-1], second last item has index
[-2], third last item has index [-3] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[-1]) # Similar to print(country[len(country) - 1])
print(country[-3])
print(country[-4])
Output:
Germany
India
Italy
III. Check for item:
We can check if a given item is present in the tuple. This is done using the in
keyword.
Example 1:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Germany" in country:
print("Germany is present.")
else:
print("Germany is absent.")
Output:
Germany is present.
Syntax:
Tuple[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: Printing all element from a given index till the end
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
Output:
('pig', 'horse', 'donkey', 'goat', 'cow')
('horse', 'donkey', 'goat', 'cow')
When no end index is provided, the interpreter prints all the values till the end.
String formatting in
python
String formatting can be done in python using the format method.
When we prefix the string with the letter 'f', the string becomes the f-string
itself. The f-string can be formatted in much same as the str.format() method. The
f-string offers a convenient way to embed Python expression inside string literals
for formatting.
Example
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Hello, My name is Tushar and I'm 23 years old.
In the above code, we have used the f-string to format the string. It evaluates at
runtime; we can put all valid Python expressions in them.
Recursion in python
Recursion is the process of defining something in terms of itself.
# Driver Code
num = 7;
print("Number: ",num)
print("Factorial: ",factorial(num))
Output:
number: 7
Factorial: 5040
Python Sets
Sets are unordered collection of data items. They store multiple items in a single
variable. Set items are separated by commas and enclosed within curly brackets {}.
Sets are unchangeable, meaning you cannot change items of the set once created.
Sets do not contain duplicate items.
Example:
info = {"Carla", 19, False, 5.9, 19}
print(info)
Output:
{False, 19, 5.9, 'Carla'}
Here we see that the items of set occur in random order and hence they cannot be
accessed using index numbers. Also sets do not allow duplicate values.
Quick Quiz: Try to create an empty set. Check using the type() function whether the
type of your variable is a set
Example:
info = {"Carla", 19, False, 5.9}
for item in info:
print(item)
Output:
False
Carla
19
5.9
Joining Sets
Sets in python more or less work in the same way as sets in mathematics. We can
perform operations like union and intersection on the sets just like in
mathematics.
I. union() and
update():
The union() and update() methods prints all items that are present in the two sets.
The union() method returns a new set whereas update() method adds item into the
existing set from another set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.union(cities2)
print(cities3)
Output:
{'Tokyo', 'Madrid', 'Kabul', 'Seoul', 'Berlin', 'Delhi'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.update(cities2)
print(cities)
Output:
{'Berlin', 'Madrid', 'Tokyo', 'Delhi', 'Kabul', 'Seoul'}
II. intersection
and intersection_update():
The intersection() and intersection_update() methods prints only items that are
similar to both the sets.
The intersection() method returns a new set whereas intersection_update() method
updates into the existing set from another set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.intersection(cities2)
print(cities3)
Output:
{'Madrid', 'Tokyo'}
Example :
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.intersection_update(cities2)
print(cities)
Output:
{'Tokyo', 'Madrid'}
III.
symmetric_difference and symmetric_difference_update():
The symmetric_difference() and symmetric_difference_update() methods prints only
items that are not similar to both the sets.
The symmetric_difference() method returns a new set whereas
symmetric_difference_update() method updates into the existing set from another
set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.symmetric_difference(cities2)
print(cities3)
Output:
{'Seoul', 'Kabul', 'Berlin', 'Delhi'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.symmetric_difference_update(cities2)
print(cities)
Output:
{'Kabul', 'Delhi', 'Berlin', 'Seoul'}
IV. difference()
and difference_update():
The difference() and difference_update() methods prints only items that are only
present in the original set and not in both the sets.
The difference() method returns a new set whereas difference_update() method
updates into the existing set from another set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = cities.difference(cities2)
print(cities3)
Output:
{'Tokyo', 'Madrid', 'Berlin'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
print(cities.difference(cities2))
Output:
{'Tokyo', 'Berlin', 'Madrid'}
Set Methods
There are several in-built methods used for the manipulation of set.They are
explained below
isdisjoint():
The isdisjoint() method checks if items of given set are present in another set.
This method returns False if items are present, else it returns True.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
print(cities.isdisjoint(cities2))
Output:
False
issuperset():
The issuperset() method checks if all the items of a particular set are present in
the original set. It returns True if all the items are present, else it returns
False.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities.issuperset(cities2))
cities3 = {"Seoul", "Madrid","Kabul"}
print(cities.issuperset(cities3))
Output:
False
False
issubset():
The issubset() method checks if all the items of the original set are present in
the particular set. It returns True if all the items are present, else it returns
False.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Delhi", "Madrid"}
print(cities2.issubset(cities))
Output:
True
add()
If you want to add a single item to the set use the add() method.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)
Output:
{'Tokyo', 'Helsinki', 'Madrid', 'Berlin', 'Delhi'}
update()
If you want to add more than one item, simply create another set or any other
iterable object(list, tuple, dictionary), and use the update() method to add it
into the existing set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Helsinki", "Warsaw", "Seoul"}
cities.update(cities2)
print(cities)
Output:
{'Seoul', 'Berlin', 'Delhi', 'Tokyo', 'Warsaw', 'Helsinki', 'Madrid'}
remove()/discard()
We can use remove() and discard() methods to remove items form list.
Example :
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)
Output:
{'Delhi', 'Berlin', 'Madrid'}
The main difference between remove and discard is that, if we try to delete an item
which is not present in set, then remove() raises an error, whereas discard() does
not raise any error.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Seoul")
print(cities)
Output:
KeyError: 'Seoul'
pop()
This method removes the last item of the set but the catch is that we don’t know
which item gets popped as sets are unordered. However, you can access the popped
item if you assign the pop() method to a variable.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)
Output:
{'Tokyo', 'Delhi', 'Berlin'} Madrid
del
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
Output:
NameError: name 'cities' is not defined We get an error because our entire set has
been deleted and there is no variable called cities which contains a set.
What if we don’t want to delete the entire set, we just want to delete all items
within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)
Output:
set()
Check
if item exists
You can also check if an item exists in the set or not.
Example
info = {"Carla", 19, False, 5.9}
if "Carla" in info:
print("Carla is present.")
else:
print("Carla is absent.")
Output:
Carla is present.
Python Dictionaries
Dictionaries are ordered collection of data items. They store multiple items in a
single variable. Dictionary items are key-value pairs that are separated by commas
and enclosed within curly brackets {}.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
Accessing Dictionary items:
I.
Accessing single values:
Values in a dictionary can be accessed using keys. We can access dictionary values
by mentioning keys either in square brackets or by using get method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
Output:
Karan
True
II.
Accessing multiple values:
We can print all the values in the dictionary using values() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
Output:
dict_values(['Karan', 19, True])
III.
Accessing keys:
We can print all the keys in the dictionary using keys() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
Output:
dict_keys(['name', 'age', 'eligible'])
IV. Accessing key-value pairs:
We can print all the key-value pairs in the dictionary using items() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
Output:
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
Dictionary Methods
Dictionary uses several built-in methods for manipulation.They are listed below
update()
The update() method updates the value of the key provided to it if the item already
exists in the dictionary, else it creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
Removing items from dictionary:
There are a few methods that we can use to remove items from dictionary.
clear():
The clear() method removes all the items from the list.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
Output:
{}
pop():
The pop() method removes the key-value pair whose key is passed as a parameter.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
Output:
{'name': 'Karan', 'age': 19}
popitem():
The popitem() method removes the last key-value pair from the dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
del:
we can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
If key is not provided, then the del keyword will delete the dictionary entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info
print(info)
Output:
NameError: name 'info' is not defined