Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Programming For Ai Sir Mids

This document provides an overview of Python programming language including what Python is, why Python is popular, Python syntax compared to other languages, variables and data types in Python. It explains print functions, variables, data types, type casting, scope of variables and different ways to output values. The document also contains code examples of key concepts.

Uploaded by

websyard
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Programming For Ai Sir Mids

This document provides an overview of Python programming language including what Python is, why Python is popular, Python syntax compared to other languages, variables and data types in Python. It explains print functions, variables, data types, type casting, scope of variables and different ways to output values. The document also contains code examples of key concepts.

Uploaded by

websyard
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

e-1-variables-datatype-casting-1

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.

File "<ipython-input-5-a5e3339f4caa>", line 2


print("Hello") # error because we have to add indentation before this line.
^
IndentationError: expected an indented block

[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

4.1 Variable names


• a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules
for Python variables:
• must start with a letter or the underscore character
• cannot start with a number
• can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• case-sensitive (age, Age and AGE are three different variables)

[11]: myvar = "John"


my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

3
[12]: 2myvar = "John"
my-var = "John"
my var = "John"

File "<ipython-input-12-0e82719f22b4>", line 1


2myvar = "John"
^
SyntaxError: invalid syntax

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)

4.4 2: Check type


[15]: print(type(a))
print(type(b))
print(type(c))

<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

4.7 5: Writing Styles


[18]: myVariableName = "John" # Camal Case
MyVariableName = "John" # Pascal case
my_variable_name = "John" # Snake case

4.8 6: Multiple and single Values assignment


[6]: x, y, z = "Orange", "Banana", "Cherry"
print(x) # Make sure the number of variables matches the number of values,
print(y) # or else you will get an error.
print(z)

print(x, "is " ,y, "are ", z)

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'

4.11 9: Globle Variables


Global variables can be used by everyone, both inside of functions and outside.

All of the above examples are globle variables.


[8]: x = "awesome"
def myfunc():
print("Python is " + x)

myfunc()

Python is awesome

4.11.1 Scope of varibale

[27]: x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

Python is fantastic
Python is awesome

4.11.2 Globle Keyword

[10]: def myfunc():


global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python is fantastic

[1]: def myfunc():


# global k
k = "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)

NameError: name 'k' is not defined

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

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

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

6 Generate Random Number


Python does not have a random() function to make a random number, but Python has a built-in
module called random that can be used to make random numbers:
[2]: import random
random.random()

[2]: 0.847536011126503

[1]: import random


random.randint(1, 100)

[1]: 86

[2]: random.randint(1, 100)

[2]: 19

[3]: print(random.randrange(1, 10))

print(random.randrange(1, 10, 2))

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)

1st shuffle [23, 67, 65, 43, 45, 12]


2nd shuffle [67, 65, 45, 23, 12, 43]
3rd shuffle [65, 23, 67, 45, 12, 43]

[1]: import random # Add random library


# https://www.tutorialsteacher.com/python/random-module

print(random.randrange(1, 10)) # generate only one number from 1 to 10

[10]: a = input("Enter number: ")

Enter number: 10

[11]: print(a)

11
10

[5]: b = input(" Enter multiple values : ")

Enter multiple values : 1 2 3 4 5 6 7 8

[6]: b

[6]: '1 2 3 4 5 6 7 8'

[7]: c = b.split()

[8]: c

[8]: ['1', '2', '3', '4', '5', '6', '7', '8']

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

[29]: for j in list2:


if j%2==0:
print("even = ", j)
if j%2 != 0:
print("Odd = ", j)

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

2 Multi line strings


[2]: # Use three double or single quotes for the paragragh or multiline string
a = """Object-oriented programming (OOP) is a computer programming model
that organizes software design around data, or objects,
rather than functions and logic.
An object can be defined as a data field
that has unique attributes and behavior."""
print(a)

Object-oriented programming (OOP) is a computer programming model


that organizes software design around data, or objects,
rather than functions and logic.
An object can be defined as a data field
that has unique attributes and behavior.

[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.

3 Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.
However, Python does not have a character data type, a single character is simply a string with a
length of 1.
Square brackets can be used to access elements of the string.
[6]: a = "Hello World"
print(a[2])
print(a[0])
print(a[7])

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

[5]: greet[0] ='A' # Does not support this assignment

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-f7322ddd5baa> in <module>
----> 1 greet[0] ='A' # Does not support this assignment

TypeError: 'str' object does not support item assignment

[7]: from IPython.display import display, Image


display(Image(filename='escap_sequence.png'))

4 Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.

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.

[10]: a = "Hello, World!"


print(len(a))

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

[13]: txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")
else:
print("no, its not present")

Yes, 'free' is present.

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

[14]: txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

No, 'expensive' is NOT present.

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!

9 Slice From the Start


By leaving out the start index, the range will start at the first character:

5
[18]: b = "Hello, World!"
print(b[:5]) # value with index 5 not involved itself

Hello

10 Slice To the End


By leaving out the end index, the range will go to the end:
[19]: b = "Hello, World!"
print(b[2:])

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

[2]: b = "Hello, World!"


print(b[-5:-1])

orld

12 Upper and Lower Case


[24]: a = "Hello World"
print(a.upper())

HELLO WORLD

[25]: a = "Hello World"


print(a.lower())

hello world

[3]: a = "Hello World"


print(a.capitalize())

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:

[16]: a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Hello, World!

14 Replace String
The replace() method replaces a string with another string:

[35]: a = "Hello, HWorldH!"


print(a)
print(a.replace("H", "J"))

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."

print(a.split(" ")) # returns ['Hello', ' World!']

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

[31]: a = "Hello" # To add a space between them, add a " ":


b = "World"

7
c = a + " " + b
print(c)

Hello World

17 Question: Count the number of vowels in a given string.


[1]: def count_vowels(string):
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
return count

input_string = "Hello World"


print("Number of vowels:", count_vowels(input_string))

Number of vowels: 3

18 Question: Check if a string is a palindrome.


[2]: def is_palindrome(string):
string = string.lower()
reversed_string = string[::-1]
return string == reversed_string

input_string = "racecar"
print("Is the string a palindrome?", is_palindrome(input_string))

Is the string a palindrome? True

19 Question: Remove all vowels from a string.


[3]: def remove_vowels(string):
vowels = "aeiouAEIOU"
return "".join(char for char in string if char not in vowels)

input_string = "Hello World"


print("String without vowels:", remove_vowels(input_string))

String without vowels: Hll Wrld

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_string = "Hello World"


print("Reversed words:", reverse_words(input_string))

Reversed words: World Hello

21 Question: Check if two strings are anagrams of each other.


[5]: def are_anagrams(str1, str2):
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
return sorted(str1) == sorted(str2)

input_string1 = "listen"
input_string2 = "silent"
print("Are the strings anagrams?", are_anagrams(input_string1, input_string2))

Are the strings anagrams? True

[ ]:

[ ]:

22 Python has a set of built-in methods that you can use on


strings.
Note: All string methods returns new values. They do not change the original string.
Method Description * capitalize()
Converts the first character to upper case * casefold()
Converts string into lower case * center()
Returns a centered string * count()
Returns the number of times a specified value occurs in a string * encode()
Returns an encoded version of the string * endswith()
Returns true if the string ends with the specified value * expandtabs()
Sets the tab size of the string * find()
Searches the string for a specified value and returns the position of where it was found * format()
Formats specified values in a string * format_map()
Formats specified values in a string * index()
Searches the string for a specified value and returns the position of where it was found * isalnum()

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]: # != Not equal


x != y

[16]: True

[17]: # > Greater than


x > y

[17]: True

[19]: # < Less than


x < y

[19]: False

[20]: # >= Greater than or equal to


x >= y

[20]: True

[21]: # <= Less than or equal to


x <= y

[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

List_variable = ['List', 'tuple','set', 'dictionary']


string = 'List' # a string to find in list_variable
string in List_variable # it prints True because it finds the "List" in␣
↪list_variable

[30]: True

[31]: # not in Returns True if a sequence with the specified value is not present in␣
↪the object

string not in List_variable

[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]: thislist = ["apple", "banana", "cherry"]


print(thislist)

['apple', 'banana', 'cherry']

1
[2]: #Duplication allowed
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

['apple', 'banana', 'cherry', 'apple', 'cherry']

5 Len
[3]: len(thislist)

[3]: 5

6 Question: Find the average of elements in a list.


[2]: # List of numbers
input_list = [1, 2, 3, 4, 5]

# Calculate the average


average = sum(input_list) / len(input_list)

# Print the average


print("Average of elements:", average)

Average of elements: 3.0

7 List Items - Data Types


List items can be of any data type:
[4]: list1 = ["apple", "banana", "cherry"]
print("list1 = ", list1)

list2 = [1, 5, 7, 9, 3]
print("list2 = ", list2)

list3 = [True, False, False]


print("list3 = ", list3)

list1 = ['apple', 'banana', 'cherry']


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

[ ]:

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)

list1 = ['abc', 34, True, 40.23, 'male']

8 type()
From Python’s perspective, lists are defined as objects with the data type ‘list’:
[6]: type(list1)

[6]: list

9 The list() function


It is also possible to use the list() constructor when creating a new list. Using the list() function
to make a List:
[11]: T = ("apple", "banana", "cherry")

print("Type of T variable is = " , type(T))


print(T) # it displays tuple

thislist = list(T) # note the double round-brackets


print(thislist) # it displays list after converted using list(T) function.
print("Type of T variable is = " , type(thislist))

Type of T variable is = <class 'tuple'>


('apple', 'banana', 'cherry')
['apple', 'banana', 'cherry']
Type of T variable is = <class 'list'>

10 Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.

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:

[1]: thislist = ["apple", "banana", "cherry"]


print(thislist[0])

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

['cherry', 'orange', 'kiwi']

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":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

4
print(thislist[:4]) # it prints values from the start to the index 3 instead of␣
↪4

['apple', 'banana', 'cherry', 'orange']

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:

[10]: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])

['cherry', 'orange', 'kiwi', 'melon', 'mango']

14.1 Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
This example returns the items from “orange” (-4) to, but NOT including “mango” (-1):

[11]: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])

['orange', 'kiwi', 'melon']

15 Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
[14]: # Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Yes, 'apple' is in the fruits list

16 Change Item Value


To change the value of a specific item, refer to the index number:
[23]: thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

['apple', 'blackcurrant', 'cherry']

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:

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

['apple', 'blackcurrant', 'watermelon', 'cherry']

[1]: # Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]


thislist[1] = ["blackcurrant", "watermelon"]
print(thislist)

['apple', ['blackcurrant', 'watermelon'], 'cherry']

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:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)

['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:

[29]: # Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]


thislist.insert(2, "watermelon")
print(thislist)

['apple', 'banana', 'watermelon', 'cherry']

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:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

['apple', 'banana', 'cherry', 'orange']

20 Insert Items
To insert a list item at a specified index, use the insert() method.

20.0.1 The insert() method inserts an item at the specified index:

[31]: # Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

['apple', 'orange', 'banana', 'cherry']

21 Extend List
To append elements from another list to the current list, use the extend() method.

[33]: # Add the elements of tropical to thislist:

list1 = ["apple", "banana", "cherry"]


list2 = ["mango", "pineapple", "papaya"]
list1.extend(list2)
print(thislist)

7
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

22 Add Any Iterable


22.0.1 The extend() method does not have to append lists, you can add any iterable
object (tuples, sets, dictionaries etc.).

[35]: # Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]


thistuple = ("kiwi", "orange") # add this tuple values to the list in the last
thislist.extend(thistuple)
print(thislist)

['apple', 'banana', 'cherry', 'kiwi', 'orange']

23 Remove Specified Item


23.0.1 The remove() method removes the specified item.

[37]: # Remove "banana":

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

['apple', 'cherry']

24 Remove Specified Index


The pop() method removes the specified index.

[1]: # Remove the second item:

thislist = ["apple", "banana", "cherry"]


a = thislist.pop(1)
print(thislist)
print(a)

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

26 The del keyword also removes the specified index:


Remove the first item:
[41]: thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

['banana', 'cherry']

27 The del keyword can also delete the list completely.

28 Delete the entire list:


[42]: thislist = ["apple", "banana", "cherry"]
del thislist

[43]: print(thislist)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-43-3e798f18ffca> in <module>
----> 1 print(thislist)

NameError: name 'thislist' is not defined

[ ]:

28.1 Question: Rotate a list to the left by a specified number of positions.


[6]: # List of numbers
input_list = [1, 2, 3, 4, 5]
positions_to_rotate = 2

# Rotate the list


rotated_list = input_list[positions_to_rotate:] + input_list[:
↪positions_to_rotate]

# Print the rotated list

9
print("List after left rotation:", rotated_list)

List after left rotation: [3, 4, 5, 1, 2]

29 Question: Find the median of elements in a list.


[7]: # List of numbers
input_list = [1, 2, 3, 4, 5]
n = len(input_list)

# Find the median


sorted_list = sorted(input_list)
if n % 2 == 0:
median = (sorted_list[n//2 - 1] + sorted_list[n//2]) / 2
else:
median = sorted_list[n//2]

# Print the median


print("Median of elements:", median)

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

# Find pairs with sum


pairs = [(input_list[i], input_list[j]) for i in range(len(input_list))
for j in range(i+1, len(input_list)) if input_list[i] + input_list[j]␣
↪== target_sum]

# Print the pairs


print("Pairs with sum:", pairs)

Pairs with sum: [(1, 5), (2, 4)]

[ ]:

[ ]:

[ ]:

10
30 Clear the List
The clear() method empties the list.

The list still remains, but it has no content.

30.0.1 Clear the list content:


[44]: thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

[]

31 Loop Through a List

32 You can loop through the list items by using a for loop
[45]: # Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

apple
banana
cherry

33 Loop Through the Index Numbers


33.0.1 You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
[17]: # Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])

apple
banana
cherry

[ ]:

[ ]:

11
[ ]:

[ ]:

34 Using a While Loop


34.0.1 Use the len() function to determine the length of the list, then start at 0 and
loop your way through the list items by refering to their indexes.
34.1 Remember to increase the index by 1 after each iteration.
[47]: # Print all items, using a while loop to go through all the index numbers

thislist = ["apple", "banana", "cherry"]


i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

apple
banana
cherry

35 Looping Using List Comprehension


List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list. A short hand for loop that will print all items in a list:
[54]: thislist = ["apple", "banana", "cherry"]
[x for x in thislist]

[54]: ['apple', 'banana', 'cherry']

[53]: s = [x for x in thislist]


print(s)

['apple', 'banana', 'cherry']

[5]: thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]

apple
banana
cherry

[5]: [None, None, None]

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

# Remove divisible elements


input_list = [x for x in input_list if x % divisor != 0]

# Print the updated list


print("List after removing divisible elements:", input_list)

List after removing divisible elements: [1, 3, 5]

[ ]:

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)

['apple', 'banana', 'mango']

36.1.1 using comprehension

[6]: fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

['apple', 'banana', 'mango']

13
[7]: newlist = [x for x in fruits if x != "apple"]
print(newlist)

['banana', 'cherry', 'kiwi', 'mango']

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:

newlist = [x for x in range(10)]


print(newlist)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[59]: # Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 5]


print(newlist)

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

['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']

[9]: fruits.upper()

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-e82645e1e1ea> in <module>
----> 1 fruits.upper()

AttributeError: 'list' object has no attribute 'upper'

[5]: newlist = [x.lower() for x in fruits]


print(newlist)

14
['apple', 'banana', 'cherry', 'kiwi', 'mango']

[6]: newlist = [x.capitalize() for x in fruits]


print(newlist)

['Apple', 'Banana', 'Cherry', 'Kiwi', 'Mango']

[63]: newlist = ['hello' for x in fruits]


print(newlist)
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)

['hello', 'hello', 'hello', 'hello', 'hello']


['apple', 'orange', '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']

38.1 Question: Check if a list contains only unique elements.


[5]: # List of numbers
input_list = [1, 2, 3, 4, 5]

# Check for uniqueness


is_unique = len(input_list) == len(set(input_list))

# Print the result


print("Does the list have unique elements?", is_unique)

Does the list have unique elements? True

[ ]:

15
[ ]:

39 Sort List Alphanumerically


39.0.1 List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:

[65]: # Sort the list alphabetically: according to the first letter of the word

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

['banana', 'kiwi', 'mango', 'orange', 'pineapple']

[7]: thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

[23, 50, 65, 82, 100]

40 Sort Descending
40.0.1 To sort descending, use the keyword argument reverse = True:

[68]: # Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

['pineapple', 'orange', 'mango', 'kiwi', 'banana']

[75]: # Sort the list descending:

thislist = [23, 65, 50, 82, 100]


thislist.sort(reverse = True)
print(thislist)

[100, 82, 65, 50, 23]

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:])

# Print the merged list


print("Merged sorted list:", merged_list)

Merged sorted list: [1, 2, 3, 4, 5, 6]

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:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.reverse()
print(thislist)

['cherry', 'Kiwi', 'Orange', 'banana']

41.2 Question: Reverse a list.


[3]: # List of numbers
input_list = [1, 2, 3, 4, 5]

# Reverse the list


reversed_list = input_list[::-1]

# Print the reversed list


print("Reversed list:", reversed_list)

Reversed list: [5, 4, 3, 2, 1]

[ ]:

42 Customize Sort Function


You can also customize your own function by using the keyword argument key = function.
The function will return a number that will be used to sort the list (the lowest number first):

[1]: # Sort the list based on how close the number is to 50:

def myfunc(n):
return abs(n - 50)

#The Python abs() method returns the absolute value of a number.


# The absolute value of a number is the number's distance from 0.
# This makes any negative number positive, while positive numbers are␣
↪unaffected.

# For example, abs(-9) would return 9, while abs(2) would return 2

18
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)

[50, 65, 23, 82, 100]

43 Case Insensitive Sort


43.0.1 By default the sort() method is case sensitive, resulting in all capital letters
being sorted before lower case letters:

[81]: # Case sensitive sorting can give an unexpected result:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.sort()
print(thislist)

['Kiwi', 'Orange', 'banana', 'cherry']

44 Luckily we can use built-in functions as key functions when


sorting a list.
44.0.1 So if you want a case-insensitive sort function, use str.lower as a key function:
44.1 Perform a case-insensitive sort of the list:
[6]: thislist = ["banana", "Orange","orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

['Kiwi', 'Orange', 'banana', 'cherry', 'orange']

45 Question: Find the second largest element in a list.


[ ]: # List of numbers
input_list = [10, 25, 7, 42, 15]

# Find the second largest element


second_largest = sorted(input_list)[-2]

# Print the second largest element


print("Second largest element:", second_largest)

[ ]:

[ ]:

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().

[84]: # Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]


mylist = thislist.copy()
print(mylist)

['apple', 'banana', 'cherry']

46.0.1 Another way to make a copy is to use the built-in method list().

[85]: # Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

['apple', 'banana', 'cherry']

47 Join Two Lists


• There are several ways to join, or concatenate, two or more lists in Python.
• One of the easiest ways are by using the + operator.
[14]: # Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

['a', 'b', 'c', 1, 2, 3]

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:

[88]: list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

['a', 'b', 'c', 1, 2, 3]

49 Or you can use the extend() method, which purpose is to add


elements from one list to another list:
49.0.1 Use the extend() method to add list2 at the end of list1:

[89]: list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

['a', 'b', 'c', 1, 2, 3]

50 All built_in Function using in List


[91]: from IPython.display import display, Image
display(Image(filename='builtin_functions.png'))

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]

Dict = {1: 'A', 2: 'For', 3: 'B'}

print("\nDictionary with the use of Integer Keys: ")


print(Dict)

print(Dict.values())
print(Dict.keys())

Dictionary with the use of Integer Keys:


{1: 'A', 2: 'For', 3: 'B'}
dict_values(['A', 'For', 'B'])
dict_keys([1, 2, 3])

[12]: # Creating a Dictionary


# with Mixed keys
Dict = {'Name': ['Ali','ahmed', 'shoib'] , 'roll no' : [1, 23, 12]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

1
Dictionary with the use of Mixed Keys:
{'Name': ['Ali', 'ahmed', 'shoib'], 'roll no': [1, 23, 12]}

[13]: # Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# 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:
{}

Dictionary with the use of dict():


{1: 'BSAI', 2: 'For', 3: 'AI'}

Dictionary with each item as a pair:


{1: 'BSAI', 2: 'For'}

3 Adding elements to a Dictionary


In Python Dictionary, the Addition of elements can be done in multiple ways. One value at a
time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.
Nested key values can also be added to an existing Dictionary.
[15]: # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'AI'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")

2
print(Dict)

# Adding set of values


# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{1 : 'Life', 2 : 'BSAI'}}
print("\nAdding a Nested Key: ")
print(Dict)

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'AI', 2: 'For', 3: 1}

Dictionary after adding 3 elements:


{0: 'AI', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'AI', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'AI', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {1: 'Life',
2: 'BSAI'}}}

4 Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
[15]: # Python program to demonstrate
# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'BSAI', 'name': 'For', 3: 'AI'}

# accessing a element using key


print("Accessing a element using key:")

3
print(Dict['name'])

# accessing a element using key


print("Accessing a element using key:")
print(Dict[1])

Accessing a element using key:


For
Accessing a element using key:
BSAI

[16]: # Creating a Dictionary


Dict = {1: 'AI', 'name': 'For', 3: 'BSAI'}

# accessing a element using get()


# method
print("Accessing a element using get:")
print(Dict.get(3))

Accessing a element using get:


BSAI

5 Accessing an element of a nested dictionary


In order to access the value of any key in the nested dictionary, use indexing [] syntax.

[17]: # Creating a Dictionary


Dict = {'Dict1': {1: 'AI'},
'Dict2': {'Name': 'For'}}

# Accessing element using key


print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['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

[22]: {'child1': {'name': 'Emil', 'year': 2004},


'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}

6 Removing Elements from Dictionary


6.1 Using del keyword
In Python Dictionary, deletion of keys can be done by using the del keyword. Using the del keyword,
specific values from a dictionary as well as the whole dictionary can be deleted. Items in a Nested
dictionary can also be deleted by using the del keyword and providing a specific nested key and
particular key to be deleted from that nested Dictionary.
[18]: # Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'BSAI',
'A' : {1 : 'BSAI', 2 : 'For', 3 : 'AI'},
'B' : {1 : 'Amazing', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)

5
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

# Deleting a Key from


# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

Initial Dictionary:
{5: 'Welcome', 6: 'To', 7: 'BSAI', 'A': {1: 'BSAI', 2: 'For', 3: 'AI'}, 'B': {1:
'Amazing', 2: 'Life'}}

Deleting a specific key:


{5: 'Welcome', 7: 'BSAI', 'A': {1: 'BSAI', 2: 'For', 3: 'AI'}, 'B': {1:
'Amazing', 2: 'Life'}}

Deleting a key from Nested Dictionary:


{5: 'Welcome', 7: 'BSAI', 'A': {1: 'BSAI', 3: 'AI'}, 'B': {1: 'Amazing', 2:
'Life'}}

7 Using pop() method


Pop() method is used to return and delete the value of the key specified.

[2]: # Creating a Dictionary


Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

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

Dictionary after deletion: {'name': 'For', 3: 'Geeks'}


Value associated to poped key is: Geeks

8 Using popitem() method


The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.

[4]: # Creating Dictionary


Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

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

Dictionary after deletion: {1: 'Geeks', 'name': 'For'}


The arbitrary pair returned is: (3, 'Geeks')

9 Using clear() method


All the items from a dictionary can be deleted at once by using clear() method.

[1]: # Creating a Dictionary


Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

Deleting Entire Dictionary:


{1: 'Geeks', 'name': 'For', 3: 'Geeks'}

10 Built in Function
[8]: str(Dict)

[8]: "{1: 'Geeks', 'name': 'For'}"

[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()

TypeError: fromkeys expected at least 1 arguments, got 0

[17]: from IPython.display import display, Image


display(Image(filename='dictionary methods.png'))

[18]: x = ('key1', 'key2', 'key3')


y = 0

thisdict = dict.fromkeys(x, y)

print(thisdict)

{'key1': 0, 'key2': 0, 'key3': 0}

[19]: x = ('key1', 'key2', 'key3')

thisdict = dict.fromkeys(x)

8
print(thisdict)

{'key1': None, 'key2': None, 'key3': None}

[20]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x)

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

[2]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}

x = car.items()

car["year"] = 2018

print(x)

dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018), ('persons',


{'Ali': 2, 'ahmed': 3, 'bilal': 4})])

[ ]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}

# car = ["a", "b" , "c"]

for i,j in car.items():

9
print(i)
print(j)

10.1 Question: Count the occurrence of each unique value in a dictionary.


[2]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 2}

# Count occurrence of each value


occurrence_count = {}
for value in my_dict.values():
occurrence_count[value] = occurrence_count.get(value, 0) + 1

# Print the occurrence count


print("Occurrence count of each unique value:", occurrence_count)

Occurrence count of each unique value: {1: 2, 2: 2}

10.2 Question: Calculate the sum of all values in a dictionary.


[3]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Calculate the sum of values


sum_of_values = sum(my_dict.values())

# Print the sum


print("Sum of all values in the dictionary:", sum_of_values)

Sum of all values in the dictionary: 6

10.3 Question: Get the keys of a dictionary as a list.


[4]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Get the keys as a list


keys_list = list(my_dict.keys())

# Print the keys list


print("Keys of the dictionary:", keys_list)

Keys of the dictionary: ['a', 'b', 'c']

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

# Check if the value exists


if value_to_check in my_dict.values():
print("Value '{}' exists in the dictionary.".format(value_to_check))
else:
print("Value '{}' does not exist in the dictionary.".format(value_to_check))

Value '2' exists in the dictionary.

10.5 Question: Find the key with the maximum value in a dictionary.
[6]: # Dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30}

# Find the key with the maximum value


max_key = max(my_dict, key=my_dict.get)

# Print the key with the maximum value


print("Key with the maximum value:", max_key)

Key with the maximum value: c

10.6 Question: Merge two dictionaries.


[7]: # Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Merge the dictionaries


merged_dict = {**dict1, **dict2}

# Print the merged dictionary


print("Merged dictionary:", merged_dict)

Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

10.7 Question: Remove a key-value pair from a dictionary.


[8]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_remove = 'b'

# Remove the key-value pair

11
my_dict.pop(key_to_remove, None)

# Print the updated dictionary


print("Dictionary after removing key '{}':".format(key_to_remove), my_dict)

Dictionary after removing key 'b': {'a': 1, 'c': 3}

10.8 Question: Get the value corresponding to a specific key in a dictionary.


[10]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_get = 'b'

# Get the value corresponding to the key


value = my_dict.get(key_to_get)

# Print the value


print("Value corresponding to key '{}':".format(key_to_get), value)

Value corresponding to key 'b': 2

11 Question: Check if a key exists in a dictionary.


[11]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_check = 'b'

# Check if the key exists


if key_to_check in my_dict:
print("Key '{}' exists in the dictionary.".format(key_to_check))
else:
print("Key '{}' does not exist in the dictionary.".format(key_to_check))

Key 'b' exists in the dictionary.

11.1 Question: Find the length of a dictionary.


[12]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Calculate the length of the dictionary


length = len(my_dict)

# Print the length


print("Length of the dictionary:", length)

Length of the dictionary: 3

12

You might also like