Programming For Ai Sir Mids
Programming For Ai Sir Mids
April 2, 2024
1 What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
What can Python do? * Python can be used on a server to create web applications. * Python can be
used alongside software to create workflows. * Python can connect to database systems. It can also
read and modify files. * Python can be used to handle big data and perform complex mathematics.
* Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is still
quite popular. In this tutorial Python will be written in a text editor. It is possible to write Python
in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages Python was designed for readability,
and has some similarities to the English language with influence from mathematics. Python uses
new lines to complete a command, as opposed to other programming languages which often use
semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions
and classes. Other programming languages often use curly-brackets for this purpose.
1
2 Print Message
[1]: print("Hello world")
Hello world
[ ]:
3 Indentations
[1]: if 5>2:
print("Hello")
print('hello')
Hello
hello
[3]: if(5>2):
print("Hello")
Hello
[4]: if 5>2:
print("Hello")
Hello
[5]: if 5>2:
print("Hello") # error because we have to add indentation before this line.
[7]: if 5>2:
print("2")
if 0>1:
print("Minimum 1")
[7]: if 5>2:
print("Hello")
2
if 5>2:
print("Hello")
Hello
Hello
[8]: if 5>2:
print("Hello")
if 5>2:
print("Hello")
Hello
Hello
[8]: if 5>2:
print("Hello")
print("Hello") # error because of extra indentation
Hello
Hello
4 Variables
[4]: a = 10
b = "Artificial intelligence"
print(a)
print(b)
[4]: str
3
[12]: 2myvar = "John"
my-var = "John"
my var = "John"
4.2 Overriding
[13]: a = 10
a = "Artificial intelligence"
print(a)
Artificial intelligence
4.3 1: Casting
[14]: a = str(7)
b = int(6)
c = float(5)
print("a =", a)
print("b =", b)
print("c =", c)
a = 7
b = 6
c = 5.0
[ ]: print("Hello world",a)
<class 'str'>
<class 'int'>
<class 'float'>
4
4.5 3: String
[16]: x = "AI" # single quotes
y = 'AI' # double quotes
print("x = ", x)
print("y = ", y)
x = AI
y = AI
4.6 4: Case-Sensitive
[17]: x = "AI" # treat small and capital letters as a different variables
X = 'BSAI'
print("x = ", x)
print("X = ", X)
x = AI
X = BSAI
Orange
Banana
Cherry
Orange is Banana are Cherry
[20]: x = y = z = "Orange"
print(x)
print(y)
print(z)
5
Orange
Orange
Orange
4.9 7: Unpacking
Python allows you extract the values into variables. This is called unpacking.
[21]: fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
apple
banana
cherry
4.10 8: Output
[22]: x = "awesome"
print("Python is " + x)
Python is awesome
[23]: x = "Python is " #You can also use the + character to add a variable to␣
↪another variable
y = "awesome"
z = x + y
print(z)
Python is awesome
[24]: x = 5
y = 10
print(x + y)
15
[25]: x = 5
y = "John"
print(x + y)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-00c66e4310ff> in <module>
1 x = 5
2 y = "John"
----> 3 print(x + y)
6
TypeError: unsupported operand type(s) for +: 'int' and 'str'
myfunc()
Python is awesome
[27]: x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Python is fantastic
Python is awesome
myfunc()
print("Python is " + x)
Python is fantastic
7
myfunc()
print("Python is " + k)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-6968d8759574> in <module>
5 myfunc()
6
----> 7 print("Python is " + k)
5 Data types
5.1 Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
• Text Type: str
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
[31]: x = "Hello World" # str
x = 20 # int
x = 20.5 # float
x = 1j # complex
x = ["apple", "banana", "cherry"] # list
x = ("apple", "banana", "cherry") # tuple
x = range(6) # range
x = {"name" : "John", "age" : 36} # dict
x = {"apple", "banana", "cherry"} # set
x = frozenset({"apple", "banana", "cherry"}) # frozenset
x = True # bool
x = b"Hello" # bytes
x = bytearray(5) # bytearray
x = memoryview(bytes(5)) #memoryview
8
5.2 Data types casting
Specify a Variable Type
• There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals
[35]: x = str("Hello World")
x = int(20)
x = float(20.5)
x = complex(1j)
x = list(("apple", "banana", "cherry"))
x = tuple(("apple", "banana", "cherry"))
x = range(6)
x = dict(name="John", age=36)
x = set(("apple", "banana", "cherry"))
x = frozenset(("apple", "banana", "cherry"))
x = bool(5)
x = bytes(5)
x = bytearray(5)
x = memoryview(bytes(5))
[1]: x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
9
print(type(b))
print(type(c))
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
[2]: # Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
<class 'float'>
<class 'float'>
<class 'float'>
[2]: 0.847536011126503
[1]: 86
[2]: 19
10
print(random.randrange(0, 101, 10))
7
5
30
[7]: print(random.choice('computer'))
print(random.choice([12,23,45,67,65,43]))
print(random.choice((12,23,45,67,65,43)))
p
12
67
6.0.1 Shuffle
[16]: numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
print("1st shuffle",numbers)
numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
print("2nd shuffle", numbers)
numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
print("3rd shuffle", numbers)
Enter number: 10
[11]: print(a)
11
10
[6]: b
[7]: c = b.split()
[8]: c
[28]: list2 = []
for i in c:
k = int(i)
list2.append(k)
print(list2)
# c = int(b)
[1, 1, 2, 3, 4, 5, 6, 7]
Odd = 1
Odd = 1
even = 2
Odd = 3
even = 4
Odd = 5
even = 6
Odd = 7
[ ]:
12
lecture-2-strings-1
April 2, 2024
1 Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
‘hello’ is the same as “hello”.
You can display a string literal with the print() function:
[14]: print("Hello")
print('Hello')
Hello
Hello
[16]: a = "Hello world" # String type variable a that contains string "Hello"
print(a)
Hello world
[1]: str1='''This is
the first
Multi-line string.
'''
1
print(str1)
str2="""This is
the second
Multi-line
string."""
print(str2)
This is
the first
Multi-line string.
This is
the second
Multi-line
string.
l
H
o
[4]: greet='hello'
print(greet[-5])
print(greet[-4])
print(greet[-3])
print(greet[-2])
print(greet[-1])
h
e
2
l
l
o
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-f7322ddd5baa> in <module>
----> 1 greet[0] ='A' # Does not support this assignment
3
[8]: for a in "Hello world":
print(a)
H
e
l
l
o
w
o
r
l
d
[22]: a = "Hello"
len(a)
for i in range(len(a)):
print(a[i])
H
e
l
l
o
[1]: a = "Hello"
for i in range(len(a)):
print(a[i])
H
e
l
l
o
5 String Length
To get the length of a string, use the len() function.
13
4
6 Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
[8]: txt = "The best things in life are free!"
print("free" in txt)
True
7 Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not
in.
[5]: txt = "The best things in life are free !"
print("expensive" not in txt)
True
8 Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
[2]: b = "Hello, World!"
print(b[6:])
World!
5
[18]: b = "Hello, World!"
print(b[:5]) # value with index 5 not involved itself
Hello
llo, World!
11 Negative Indexing
Use negative indexes to start the slice from the end of the string:
11.1 Example
Get the characters:
From: “o” in “World!” (position -5)
To, but not included: “d” in “World!” (position -2):
orld
HELLO WORLD
hello world
Hello world
6
13 Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to remove
this space.
The strip() method removes any whitespace from the beginning or the end:
Hello, World!
14 Replace String
The replace() method replaces a string with another string:
Hello, HWorldH!
Jello, JWorldJ!
15 Split String
The split() method returns a list where the text between the specified separator becomes the list
items.
[18]: a = "The split() method returns a list where the text between the specified␣
↪separator becomes the list items."
16 String Concatenation
To concatenate, or combine, two strings you can use the + operator.
[30]: a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
7
c = a + " " + b
print(c)
Hello World
Number of vowels: 3
input_string = "racecar"
print("Is the string a palindrome?", is_palindrome(input_string))
8
20 Question: Reverse words in a given string.
[4]: def reverse_words(string):
words = string.split()
reversed_words = " ".join(words[::-1])
return reversed_words
input_string1 = "listen"
input_string2 = "silent"
print("Are the strings anagrams?", are_anagrams(input_string1, input_string2))
[ ]:
[ ]:
9
Returns True if all characters in the string are alphanumeric * isalpha()
Returns True if all characters in the string are in the alphabet * isascii()
Returns True if all characters in the string are ascii characters * isdecimal()
Returns True if all characters in the string are decimals * isdigit()
Returns True if all characters in the string are digits * isidentifier()
Returns True if the string is an identifier * islower()
Returns True if all characters in the string are lower case * isnumeric()
Returns True if all characters in the string are numeric * isprintable() Returns True if all characters
in the string are printable * isspace() Returns True if all characters in the string are whitespaces
* istitle() Returns True if the string follows the rules of a title * isupper() Returns True if all
characters in the string are upper case * join()
Converts the elements of an iterable into a string * ljust()
Returns a left justified version of the string * lower()
Converts a string into lower case * lstrip()
Returns a left trim version of the string * maketrans()
Returns a translation table to be used in translations * partition()
Returns a tuple where the string is parted into three parts * replace() Returns a string where a
specified value is replaced with a specified value * rfind()
Searches the string for a specified value and returns the last position of where it was found *
rindex()
Searches the string for a specified value and returns the last position of where it was found * rjust()
Returns a right justified version of the string * rpartition()
Returns a tuple where the string is parted into three parts * rsplit()
Splits the string at the specified separator, and returns a list * rstrip()
Returns a right trim version of the string * split()
Splits the string at the specified separator, and returns a list * splitlines()
Splits the string at line breaks and returns a list * startswith()
Returns true if the string starts with the specified value * strip()
Returns a trimmed version of the string * swapcase()
Swaps cases, lower case becomes upper case and vice versa * title()
Converts the first character of each word to upper case * translate()
Returns a translated string * upper()
Converts a string into upper case * zfill()
Fills the string with a specified number of 0 values at the beginning
[ ]:
10
lecture-3-operators-1
April 2, 2024
1 Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
2 Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations
[7]: x = 4
y = 2
# + Addition
print("Addition =" , x + y)
# - Subtraction
print("Subtraction =" ,x - y)
# * Multiplication
print("Multiplication =" ,x * y)
# / Division
print("Division =" ,x / y)
# % Modulus
print("Modulus =" ,x % y)
# ** Exponentiation
print("Exponentiation =" ,x ** y)
# // Floor division
print("Floor division =" ,x // y)
1
Addition = 6
Subtraction = 2
Multiplication = 8
Division = 2.0
Modulus = 0
Exponentiation = 16
Floor division = 2
3 Assignment Operators
[8]: # =
x = 5
print("= ", x)
# +=
x += 3
print("+=", x)
x = x + 3
print("+=",x)
# -=
x -= 3
print("-=", x)
x = x - 3
print("-=", x)
# *=
x *= 3
print("*=",x)
x = x * 3
print("*=",x)
# /=
x /= 3
print("/=",x)
x = x / 3
print("/=",x)
# %=
x %= 3
print("%=",x)
x = x % 3
print("%=",x)
# //=
x //= 3
print("//=",x)
2
x = x // 3
print("//=", x)
# **=
x **= 3
print("**",x)
x = x ** 3
print("**",x)
= 5
+= 8
+= 11
-= 8
-= 5
*= 15
*= 45
/= 15.0
/= 5.0
%= 2.0
%= 2.0
//= 0.0
//= 0.0
** 0.0
** 0.0
4 Logical Operators
[1]: # and
# Returns True if both statements are true
x = 7
if x < 5 and x < 10:
print("Hello")
[6]: # or
# Returns True if one of the statements is true
x < 5 or x < 10
[6]: True
[7]: # not
# Reverse the result, returns False if the result is true
not(x < 5 and x < 10)
[7]: True
3
5 Comparison Operator
[11]: # == Equal
x = 10
y = 5
a = 5
b = 5
print(x == y) # print False
print(a == b) # print True
False
True
[16]: True
[17]: True
[19]: False
[20]: True
[21]: False
6 Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
[2]: # is Returns True if both variables are the same object
x = 4
y = 4
x is y
4
[2]: True
[3]: # is not
# Returns True if both variables are not the same object
if x is not y:
print("hello")
7 Membership Operators
Membership operators are used to test if a sequence is presented in an object:
[30]: # in Returns True if a sequence with the specified value is present in the␣
↪object
[30]: True
[31]: # not in Returns True if a sequence with the specified value is not present in␣
↪the object
[31]: False
[ ]:
5
lecture-4-lists
April 2, 2024
1 List
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
2 List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.
2.1 Ordered
• When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
• If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the
order of the items will not change.
3 Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
4 Allow Duplicates
Since lists are indexed, lists can have items with the same value:
[ ]:
1
[2]: #Duplication allowed
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
5 Len
[3]: len(thislist)
[3]: 5
list2 = [1, 5, 7, 9, 3]
print("list2 = ", list2)
[ ]:
2
7.1 A list can contain different data types:
7.2 A list with strings, integers and boolean values:
[4]: list1 = ["abc", 34, True, 40.23, "male"]
print("list1 = ", list1)
8 type()
From Python’s perspective, lists are defined as objects with the data type ‘list’:
[6]: type(list1)
[6]: list
3
11 Operations of List
12 1 Access item
List items are indexed and you can access them by referring to the index number:
Note: The first item has index 0.
[12]: # Print the second item of the list:
apple
13 Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
[1]: # Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
cherry
14 Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
[16]: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
14.0.1 Note: The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
[8]: #This example returns the items from the beginning to, but NOT including,␣
↪"kiwi":
4
print(thislist[:4]) # it prints values from the start to the index 3 instead of␣
↪4
14.0.2 By leaving out the end value, the range will go on to the end of the list: This
example returns the items from “cherry” to the end:
5
17 Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and refer to
the range of index numbers where you want to insert the new values:
Change the values “banana” and “cherry” with the values “blackcurrant” and “watermelon”:
[1]: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = "blackcurrant"
print(thislist)
['apple', 'b', 'l', 'a', 'c', 'k', 'c', 'u', 'r', 'r', 'a', 'n', 't', 'orange',
'kiwi', 'mango']
17.0.1 If you insert more items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
[2]: # Change the second value by replacing it with two new values:
[1]: # Change the second value by replacing it with two new values:
Note: The length of the list will change when the number of items inserted does not
match the number of items replaced. If you insert less items than you replace, the new items
will be inserted where you specified, and the remaining items will move accordingly:
[27]: # Change the second and third value by replacing it with one value:
['apple', 'watermelon']
18 Insert Items
• To insert a new list item, without replacing any of the existing values, we can use the insert()
method.
6
18.0.1 The insert() method inserts an item at the specified index:
19 Append Items
To add an item to the end of the list, use the append() method:
[30]: # Using the append() method to append an item:
20 Insert Items
To insert a list item at a specified index, use the insert() method.
21 Extend List
To append elements from another list to the current list, use the extend() method.
7
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
['apple', 'cherry']
['apple', 'cherry']
banana
25 If you do not specify the index, the pop() method removes the
last item.
Remove the last item:
8
[39]: thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
['apple', 'banana']
['banana', 'cherry']
[43]: print(thislist)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-43-3e798f18ffca> in <module>
----> 1 print(thislist)
[ ]:
9
print("List after left rotation:", rotated_list)
Median of elements: 3
29.1 Question: Find all pairs of elements in a list that sum up to a specific
target value.
[8]: # List of numbers
input_list = [1, 2, 3, 4, 5]
target_sum = 6
[ ]:
[ ]:
[ ]:
10
30 Clear the List
The clear() method empties the list.
[]
32 You can loop through the list items by using a for loop
[45]: # Print all items in the list, one by one:
apple
banana
cherry
apple
banana
cherry
[ ]:
[ ]:
11
[ ]:
[ ]:
apple
banana
cherry
apple
banana
cherry
12
[ ]:
35.1 Question: Remove all elements from a list that are divisible by a specific
number.
[10]: # List of numbers
input_list = [1, 2, 3, 4, 5]
divisor = 2
[ ]:
36 Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter
“a” in the name.
36.1 Without list comprehension you will have to write a for statement with a
conditional test inside:
[50]: fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
print(newlist)
13
[7]: newlist = [x for x in fruits if x != "apple"]
print(newlist)
37 Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
[57]: # You can use the range() function to create an iterable:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
38 Expression
The expression is the current item in the iteration, but it is also the outcome, which you can
manipulate before it ends up like a list item in the new list:
[8]: # Set the values in the new list to upper case:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
print(newlist)
[9]: fruits.upper()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-e82645e1e1ea> in <module>
----> 1 fruits.upper()
14
['apple', 'banana', 'cherry', 'kiwi', 'mango']
[3]: numbers = [23, 43, 45, 65, 43, 32, 213, 67, 89, 4 ,3, 2]
even_odd = ["even" if i%2==0 else "odd" for i in numbers]
even_odd
[3]: ['odd',
'odd',
'odd',
'odd',
'odd',
'even',
'odd',
'odd',
'odd',
'even',
'odd',
'even']
[ ]:
15
[ ]:
[65]: # Sort the list alphabetically: according to the first letter of the word
40 Sort Descending
40.0.1 To sort descending, use the keyword argument reverse = True:
40.1 Question: Merge two sorted lists into a single sorted list.
[12]: # Lists of numbers
list1 = [1, 3, 5]
list2 = [2, 4, 6]
16
# Merge sorted lists
merged_list = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1
merged_list.extend(list1[i:])
merged_list.extend(list2[j:])
40.1.1 Explanation:
• We start with two sorted lists: list1 and list2.
• We create an empty list called merged_list to store the merged sorted list.
• We initialize two pointers i and j to keep track of the indices of elements in list1 and list2
respectively.
• We enter a while loop that continues until either i reaches the end of list1 or j reaches the
end of list2.
• Inside the while loop, we compare the elements at indices i and j of list1 and list2 respectively.
• If the element at index i of list1 is smaller than the element at index j of list2, we append the
element from list1 to merged_list and increment i.
• Otherwise, if the element at index j of list2 is smaller than or equal to the element at index i
of list1, we append the element from list2 to merged_list and increment j.
• After appending all elements from either list1 or list2 to merged_list, we extend merged_list
with the remaining elements of the other list that haven’t been appended yet.
• Finally, we print the merged_list, which contains the sorted elements from both list1 and
list2.
[ ]:
17
41 Reverse Order
41.0.1 What if you want to reverse the order of a list, regardless of the alphabet?
41.1 The reverse() method reverses the current sorting order of the elements.
[77]: # Reverse the order of the list items:
[ ]:
[1]: # Sort the list based on how close the number is to 50:
def myfunc(n):
return abs(n - 50)
18
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
[ ]:
[ ]:
19
[ ]:
46 Copy a List
• You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference
to list1, and changes made in list1 will automatically also be made in list2.
• There are ways to make a copy, one way is to use the built-in List method copy().
46.0.1 Another way to make a copy is to use the built-in method list().
20
48 Another way to join two lists is by appending all the items
from list2 into list1, one by one:
48.0.1 Append list2 into list1:
for x in list2:
list1.append(x)
print(list1)
list1.extend(list2)
print(list1)
21
[ ]:
50.1 Assignment 1
50.1.1 Q1: Write a program to get student information as name, cnic, father name,
semester, section, enrolled subject using lists.
50.1.2 Q2: Write a program to get 6 different subjects marks and calulate grade using
percentatge of total marks.
50.1.3 Q3: Write a program to calculate arithemtic operation +, -, *, / on two
different operands using comprehension loops.
[ ]:
[ ]:
22
lecture-5-dictionary
April 2, 2024
1 Python Dictionary
Difficulty Level : Easy Last Updated : 31 Oct, 2021 Dictionary in Python is an unordered collection
of data values, used to store data values like a map, which, unlike other Data Types that hold only a
single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary
to make it more optimized.
2 Creating a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corre-
sponding pair element being its Key:value. Values in a dictionary can be of any data type and can
be duplicated, whereas keys can’t be repeated and must be immutable.
[11]: # Creating a Dictionary
# with Integer Keys
List = [1, 3, 'as', 56]
print(Dict.values())
print(Dict.keys())
1
Dictionary with the use of Mixed Keys:
{'Name': ['Ali', 'ahmed', 'shoib'], 'roll no': [1, 23, 12]}
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'BSAI', 2: 'For', 3:'AI'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'BSAI'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Empty Dictionary:
{}
2
print(Dict)
Empty Dictionary:
{}
# Creating a Dictionary
Dict = {1: 'BSAI', 'name': 'For', 3: 'AI'}
3
print(Dict['name'])
{1: 'AI'}
AI
For
[15]: myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
4
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
[22]: child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
myfamily
5
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
Initial Dictionary:
{5: 'Welcome', 6: 'To', 7: 'BSAI', 'A': {1: 'BSAI', 2: 'For', 3: 'AI'}, 'B': {1:
'Amazing', 2: 'Life'}}
# Deleting a key
# using pop() method
pop_ele = Dict1.pop(1)
print('\nDictionary after deletion: ' + str(Dict1))
print('Value associated to poped key is: ' + str(pop_ele))
6
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))
10 Built in Function
[8]: str(Dict)
[9]: len(Dict)
[9]: 2
[10]: type(Dict)
[10]: dict
[11]: Dict.clear()
[12]: Dict.copy()
[12]: {}
7
[3]: Dict.fromkeys()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-0daed0f5138e> in <module>
----> 1 Dict.fromkeys()
thisdict = dict.fromkeys(x, y)
print(thisdict)
thisdict = dict.fromkeys(x)
8
print(thisdict)
[20]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
[2]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}
x = car.items()
car["year"] = 2018
print(x)
[ ]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}
9
print(i)
print(j)
10
10.4 Question: Check if a value exists in a dictionary.
[5]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_to_check = 2
10.5 Question: Find the key with the maximum value in a dictionary.
[6]: # Dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30}
11
my_dict.pop(key_to_remove, None)
12