0% found this document useful (0 votes)
23 views82 pages

Functions

The document is a comprehensive syllabus covering various programming concepts in Python, including functions, string manipulation, lists, tuples, dictionaries, and variable types. It explains the definition, usage, and types of functions, along with examples of built-in and user-defined functions, as well as function arguments and return values. Additionally, it discusses concepts such as anonymous functions, mutable vs immutable data types, and provides examples of string slicing and indexing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views82 pages

Functions

The document is a comprehensive syllabus covering various programming concepts in Python, including functions, string manipulation, lists, tuples, dictionaries, and variable types. It explains the definition, usage, and types of functions, along with examples of built-in and user-defined functions, as well as function arguments and return values. Additionally, it discusses concepts such as anonymous functions, mutable vs immutable data types, and provides examples of string slicing and indexing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

SYLLABUS

Functions:
Defining a function, calling a function, Types of functions, Function Arguments,
Anonymous functions, Global and local variables.
String Manipulation:
Accessing Strings, Basic Operations, String slices, Function and Methods.
Lists:
Accessing list, Operations, Working with lists Function and Methods
Tuple:
Accessing tuples, Operations, Working.
Dictionaries:
Accessing values in dictionaries, working with dictionaries, Properties Functions
and Methods.
• What is a Function ?
• Why we use functions ?
• Calling a function?
• What are the types of the functions ?
FUNCTIONS
A function is a block of reusable code used to perform specific task. Instead of writing same
code again and again for different inputs, we can do the function calls to reuse code contained
in it over and over again.
Benefits of Using Functions
Code Reuse
Reduced code length
Increased readability of code
SYNTAX:
def function_Name(parameters):
#function body
FUNCTION DECLARATION
The def keyword stands for define. It is used to create a user-defined function. It marks the
beginning of a function block and allows you to group a set of statements so they can be
reused when the function is called.
function_name: Name of the function.
parameters: Inputs passed to the function (inside ()), optional.
: : Indicates the start of the function body.
Example:
def greet():
print('hello world’)

OUTPUT: We don’t get output as the function is not called


Calling a function
After creating a function in Python we can call it by using the
name of the functions Python.
Ex1:def greet():
print('hello world’)
greet()------------------------------calling a function
OUTPUT: hello world

EX2:def sum():
a = 30
b = 20
print(a+b)
sum()
OUTPUT: 50
EX3: def message():
print("welcome to AIML")
print("First function program”)
message()
OUTPUT:welcome to AIML
First function program
TYPES OF FUNCTIONS
PRE-Defined Functions
These are Standard functions in Python that are available to use. you can use them
anywhere in your code without importing anything.
Common Built-In Functions.
Category Functions (Examples) What It Does

Math & Numbers abs(), divmod(), pow(), round() Perform common math operations

Type Conversions int(), float(), str(), list(), dict() Convert or create data types

Iteration & Collections enumerate(), zip(), map(), sorted() Process iterable data elegantly

Introspection & Debugging type(), dir(), help(), breakpoint() Explore objects or troubleshoot

I/O & Miscellaneous print(), input(), open(), eval(), exec() Handle I/O, run code dynamically
Examples for Pre-defined Function
1)abs()– The abs() function returns the absolute value of the given number
number = -20
absolute_number = abs(number)
print(absolute_number)
OutPut:20
2)Syntax : pow()
Program: print(pow(3, 4))
Output: 81
USER-defined
Functions that we define Function
ourselves as
our requirement to do certain task areper
referred as user-defined functions.
def keyword is used
a user-defined function. to create
Example: def dept() user defined function
declaration
Print(“AIML”)
dept() Function calling
Advantages of user-defined functions
User-defined
1.
into small functions
segments help
which to decompose
makes program a large
easy to program
understand, maintain and debug.
If include
2.
to repeated codecodes
those occurs in aexecute
and program. Function
when needed can
bybe used
calling
that function.
Programmers
3.
workload working
by making on large
different project can divide the
functions.
Functional Arguments and Parameters
•Parameters: A parameter is the variable listed inside the parentheses
in the function definition.
•Syntax: def my_function(Parameter1, Parameter2)
Example: def add(x, y):----------------------Here X and Y are parameters
return x + y
•Arguments: These are the actual values passed to the function when it
is called.

Example : add(10,20)--------Passing values to the add function

Here 10 and 20 are the arguments


Program showing Parameters and
arguments
def add_numbers(a, b): # a and b are parameters
return a + b
result = add_numbers(5, 3) # 5 and 3 are arguments
print(result)
# Output: 8
Using function specify whether a
given number is even or odd
def even_odd(num):
if num % 2 == 0:
print("even")
else:
print("odd")

even_odd(11)

OUTPUT:odd
FORMAL and ACTUAL Arguments
FORMAL ARGUMENTS------also called as Parameters.
These are the variable names listed in the function definition.
ACTUAL ARGUMENTS------also called as Arguments.
These are the actual values or variables you pass when you call the function.
EXAMPLE:
Function Definition Function Call
def greet(name): greet(“hello")
↑ ↑
Formal Argument Actual Argument
RETURN
Functions with return.
1)The return statement is used to exit the function
2)Go back to the place from where the function was called.
3)Any statement after the return will not execute.
4)If the return statement is without any expression then python return NONE by default.
Consider an example
def add_num(a,b):-------------#defines a function sum with two parameters a and b.

#This function can be reused to add any two numbers.


#This line adds the two inputs a and b and return the result to wherever the
function was called
return a+b -------------------- It ends the function here.

result=add_num(20,30)----calling the function with two values 20 and 30


50 is returned and stored in the variable result
print(result)
Multiple values in return
In PYTHON a function can return multiple values by separating with commas in the return
statement.
def calculations(x,y):------------takes two parameters and perform following operations
sum_values = x + y
diff_values = x - y
product_values = x * y
return sum_values, diff_values, product_values
#It calculates and returns all three values.
#Now calling the function
#Lets take three variables
a,b,c = calculations(20,30)
Print(“sum:”, a)
Print(“Difference:”, b)
Any statement after the
return will not execute
def example_function():
print("Before return")
return "Function has returned"
print("This will NOT be executed") # This line will be skipped

# Calling the function


result = example_function()
print("Returned value:", result)
FUNCTION ARGUMENTS
• The function arguments used in a function call
are of 4 types:
• Positional arguments
• Keyword arguments
• Default arguments
• Variable length arguments
POSITIONAL ARGUMENTS
Positional arguments are the arguments passed to a function in correct positional
order.
Here, the number and position of arguments in the function call should match
exactly with the function definition.
Example: def calculate_area(length, width):
return length * width
area = calculate_area(5, 10)
print(area)
length gets the value 5
width gets the value 10
Output: Area: 50
KEYWORD ARGUMENTS
Keyword arguments are arguments passed to a function by explicitly specifying the
parameter name along with its value during the function call.
This means you can provide arguments out of order because each argument is matched
to the correct parameter by its name, not position.
Example:
def describe_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}.")
This line is inside the function (indented).
It uses an f-string (formatted string literal) to create a sentence by inserting the values of
the variables name, age, and city directly into the string.
When the function runs, it will print a sentence describing the person using the values
passed in.
describe_person(city="New York", name="Bob", age=40)
DEFAULT ARGUMENTS
Default arguments are values that a function parameters take if you don’t provide a value
for them when calling the function.
They let you make some parameters optional, providing a default behavior while still
allowing callers to override them
SYNTAX: def function_name(param1, param2=default_value):
# function body
EXAMPLE: def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("HI") -----------------------output: hello HI
Here, greeting has a default value "Hello".
name has no default, so it must be provided.
VARIABLE LENGTH ARGUMENT
Sometimes you want a function that can accept any number of arguments, not just a fixed number
*args for variable-length positional arguments.
**kwargs for variable-length keyword arguments.
Example with *args
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1, 2, 3)) # Output: 6
print(add_numbers(5, 10, 15, 20)) # Output: 50
print(add_numbers()) # Output: 0
Example with **kwargs
**kwargs allows the function to accept zero or more keyword arguments.
Inside the function, kwargs is a dictionary containing the argument names and values.
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name=“snist", country=‘india’,city=“hyd")
EXPLANATION:**kwargs: This allows the function to accept any number of keyword
arguments.
kwargs stands for "keyword arguments" (not a keyword itself, just a common convention).
Inside the function, kwargs will be a dictionary where:
the keys are the names of the keyword arguments,
the values are the values passed to those arguments.
Anonymous functions
These functions are called "anonymous" because they do not have a name like regular
functions defined using def.
Anonymous functions are created using the lambda keyword.
They are often used for short, simple operations and are typically written in a single line.
SYNTAX: lambda arguments: expression
arguments: Input parameters for the function.
expression: A single expression that is evaluated and returned.

FEATURES
Single Expression: Lambda functions can only contain one expression, which is implicitly
returned.
No Name: They are unnamed and are often used as inline functions.
Use Cases: Commonly used with functions like map(), filter(), and reduce().
Basic lambda function:
square = lambda x: x ** x
print(square(5))
Output: 25

Lambda with Multiple Arguments:


add = lambda x, y,z,a,b,: x + y
print(add(3, 7))
Output: 10
Filter() function
Filter () function takes two arguments a function and iterable.
It Returns an iterator containing only those elements from the iterable where the function is returned true
SYNTAX: filter(function, iterable)
A function that returns true or false.
An iterable like tuple,dictionary
Example
ages = [5, 18, 17, 8, 24, 32]

def person(i):
if i < 18:
return False
else:
return True

adults = filter(person, ages)

for i in adults:
print(i)
OUTPUT: 18,24,32
Using a lambda function with filter
ages = [5, 18, 17, 8, 24, 32]
adults = filter(lambda i: i >= 18, ages)
for i in adults:
print(i)
PROGRAM TO PRINT EVEN NUMBERS
nums = [1, 2, 3, 4, 5, 6]
even_nums = filter(lambda x: x % 2 == 0, nums)
print(list(even_nums))
Output: [2, 4, 6]
map() Function
map() function in Python is used to apply a specific function to each element of an iterable
and returns a map object
SYNTAX: map(function, iterable,..)
function: The function to apply to every element of the iterable.
iterable: One or more iterable objects (list, tuple, etc.) whose elements will be processed
EXAMPLE:
a = [1, 2, 3, 4]
res = list(map(lambda x: x * 2, a))
print(res)
OUTPUT: [2, 4, 6, 8]
Reduce() function
The reduce() function in Python applies a given function cumulatively to all items in an
iterable, reducing g it to a single final value.
It’s a method of the functools module, so we need to import it before use:
The functools module offers a collection of tools that simplify working with functions and
callable objects. It includes utilities to modify, extend or optimize functions without
rewriting their core logic, helping you write cleaner and more efficient code.
SYNTAX:
from functools import reduce
reduce(function, iterable[, initializer])
function: A function that takes two arguments and returns a single value.
iterable: The sequence to be reduced (list, tuple, etc.).
initializer (optional): A starting value that is placed before first element.
Return Value: A single final value after processing all elements.
EXAMPLES
from functools import reduce
# Function to add two numbers
def add(x, y):
return x + y
a = [1, 2, 3, 4, 5]
res = reduce(add, a)
print(res)
OUTUT:15
Using reduce() with a Lambda Function
from functools import reduce
a = [1, 2, 3, 4, 5]
res = reduce(lambda x, y: x + y, a)
print(res)
OUTPUT:15
Global and local variables
LOCAL VARIABLE
Definition: Variables declared inside a function are local to that function. They can only be
accessed within that function.
EXAMPLE
def my_function():
x = 10 # Local variable
print("Inside the function, x =", x)

my_function()
# print(x) # This will raise an error because x is not accessible outside the function.
GLOBAL VARIABLE
DEFINITION:Variables declared outside the function are global.They can be accessed and
modified outside the function using global keyword.
EXAMPLE:
x = 20 # Global variable
def my_function():
global x # Declare x as global to modify it
x = 30
print("Inside the function, x =", x)

my_function()
print("Outside the function, x =", x)
DIFFERENCE BETWEEN LOCAL
AND GLOBAL VARIABLE
• GLOBAL VARIABLE • LOCAL VARIABLE
1)They are defined in the main 1)They are defined within a
body of the program. function and is local to that
2)They can be accessed function
throughout the program. 2)They can be accessed from the
3)Global variables are accessible point of its definition until the end
to all the functions in the of the block in which it is defined.
program. 3)They are not related in any way
to other variables with the same
names used outside the function.
Mutable V/s Immutable Data Types
MUTABLE DATA TYPE IMMUTABLE DATA TYPE

1. Sequences can be modified after creation 1. Sequences cannot be modified after creation

2. Eg: Lists, Dictionary, Sets 2. Eg: Strings, Tuple, Integer

3. We can perform add, delete and update 3. We cannot perform add, delete and update
operations operations
The index must be an integer. We can't use float or other types, this will result into Type
Error.
Positive indexes

Negative indexes
Example for access characters
in a string
Positive 0 1 2 3 4 5 6

indexing
Str W E L C O M E

Negative
-7 -6 -5 -4 -3 -2 -1
indexing

str= “WELCOME”
Print(“given string is”,str)
Print(“str[0]”,str[0])
Print(“str[-2]”,str[2])
STRING SLICING
A substring of a string is called slice. You can take subset of a string from the original
string by using[].
SYNTAX:
string [start:end:step]
Start-Index to begin
End-index to end(exclusive)
Step: interval between index

Example : str = “welcome to SNIST”


Print(str[1:5])

Output: elco
Print(str[:5])----------welco

Print(str[1:])----------elcome to SNIST

Print(str[-6:])---------- SNIST

Print(str[::2])----------wloet NS

Print(str[:5:2])----------wlo
Change or delete a
string
Strings are immutable, i.e., that elements of a string cannot be changed once it
has been assigned. We can reassign different strings to the same name.
We cannot delete or remove characters from a string, but we can delete a string
using the keyword “del”

str=“welcome”
str=“python”
str
output: python
del str
str
Concatenation of string
We can use ‘+’ on strings to attach a string at the end of another string. This operator ‘+’ is
called addition operator.
S1=“hello”
S2=“welcome”
S3=s1+s2
Print(s3)

Repeating the strings


The * operator can be used to repeat the string for a given number of times

str1="hello"
print(str1*2)
Print(str1*5)
Appending a string
Append means to add something at the end. In python you can add one string at
the end of the another string. We use += operator to append.
Str=“hello”
name= input(“enter your string”)
str += name
str +=“.Welcome to SNIST”
Print(str)
OUTPUT:
Hello one and all . Welcome to SNIST

Entered String
STRING FORMATING
The process of inserting values,variables into a string is called string formatting.
Clarity: Easier to read than string concatenation.
Flexibility: You can format numbers, dates, and text precisely
Maintainability: Code is easy to understand and easier to update.
# Without formatting
name = “snist"
Year =2025
print("Name: " + name + ", year: " + str(year))
Example programs on formatted strings
name = "SNIST"
YEAR = 2025
print(f"name = {name} and year = {YEAR}")
print(f"name = {'SREE'} and year = {2024}")
OUTPUT:
name = SNIST and year = 2025
name = SREE and year = 2024
EX2: books =2
Cost=55.5
print(f”cost of {books} is {cost}”)
Removing Spaces from string
A space is also considered as a character inside a string
This method is used to remove whitespaces from beginning to end of the string
We can use three methods:
1.rstrip() - removes spaces at right
2.lstrip() – removes spaces at left
3. strip()- removes spaces from both sides
Eg: name = " Welcome to SNIST "

print("Original string: ", repr(name))


print("After rstrip(): ", repr(name.rstrip()))
print("After lstrip(): ", repr(name.lstrip()))
print("After strip(): ", repr(name.strip()))
OUTPUT:

Original string: ' Welcome to SNIST '


After rstrip(): ' Welcome to SNIST'
After lstrip(): 'Welcome to SNIST '
After strip(): 'Welcome to SNIST’

repr()-----it is python built in function used to represent exact content especially


spaces,tabs or special characters
Replacing string with another string
The replace() method is useful to replace a sub string wit another sub string.
Eg:
str="Welcome to SNIST AIML dept"
str1 = "Welcome"
str2= "hello"
str3 = str.replace(str1, str2)
print(str)
print(str3)

OUTPUT:Welcome to SNIST AIML dept


hello to SNIST AIML dept
LISTS
List is an ordered collection of data which can be changeable and also allows duplicates. It is
represented in [] . Lists are Mutable. It consist of both integers and strings.
Example: list =[26,34,6,’hello’,’world’]

LIST ALLOWS
1)CONCATENATION.
2) Repetition of lists
3) Membership in list
4)Aliasing
5)Cloning
LISTS example:
Syntax:
a= [1,2,3,4,5]
b= [‘AIML’,1,2,3, ‘welcome’]
c= [‘val’,1,3,4,’aiml’,[10,‘aiml’,20],1] # A list within another list is Nested.
d= []
Print(a,b,c,d)

LISTS ARE MUTABLE


Lists are Mutable. i.e we after creation of a list, we can modify its content.
a= [1,2,3,4,5,"AIML","AUGUST"]
print(a[3])
a[3]=50
print(a)
Accessing values in lists
The syntax for accessing the elements of a list is the same as accessing the characters
of a string – the bracket operator []
Index values always starts from 0, we can also access a list from reverse
Python supports both positive indexing and negative indexing.
a=[‘cse’, 1,2,3,4,’june’,0]
a[2]
2
a[5]
june
ELEMENTS IN A LIST:
a=[‘cse’, 1,2,3,4,’june’,0]

a[0] = ‘cse’ =a[-7]


a[1] = 1 =a[-6]
a[2] = 2 =a[-5]
a[3] = 3 =a[-4]
a[4] = 4 =a[-3]
a[5] = ‘june’ =a[-2]
a[6] = 0 =a[-1]
List slicing
List=[start:end:stepsize]
Start: indicates the index where the slice has to start. #default value is 0
End: indicates the index where the slice has to end. #length of list
Step: increment value #default value is 1
names=[‘dp’,’pt’,’lk’,’py’,’pj’]
names[0:4]
[‘dp’,’pt’,’lk’,’py’,’pj’]
names[0:4:1]
['dp', 'pt', 'lk', 'py']
names[0:4:2]
['dp', 'lk']
names[0:4:3]
['dp', 'py']
names[:]
['dp', 'pt', 'lk', 'py', 'pj']
names[::]
['dp', 'pt', 'lk', 'py', 'pj']
Names[0:]
LIST OPERATIONS
CONCATENATION OF TWO LISTS
Eg: 1
x=[10,20,30,40,50]
y=[60,30,20,10]
print(x+y)
The concatenated list appears:
[10,20,30,40,50,60,30,20,10]
Eg:2
a=[1,2,3,’june’,6,8]
b=[4,3,9,’ds’]
print(a+b)
The concatenated list appears:
[1,2,3,’june’,6,8,4,3,9,’ds’]
Repetition of lists
We can repeat the elements of a list ‘n’ number of times using ‘*’ operator.
Eg: (a * 2)
a=[1,2,3,4,5,’june’]
print(a*2)
#repeat the list a for 2 times
a=[1,2,3,4,5,’june’, 1,2,3,4,5,’june’]
Membership in list
in and not in are boolean operators that test membership in a sequence.
We can check if an element is a member of a list or not by using in or not in operator.
If the element is a member of the list, then ‘in’ operator returns True, else False.
a= [10,20,30,40,50,’sky’]
b=20
print(b in a) #check if b is member of a
Op: True
c=‘sky’
c not in a
Op: False
METHODS TO PROCESS LIST
METHOD EXAMPLE DESCRIPTION
append() List.append(x) Appends x at the end of the list
insert() list.insert(i, x) Inserts x in to list in the specified position
by i
Copy() List.copy() Copies all the list elements into a new list
and returns it
extend() List.extend(list1)) Appends list1 to list
count() List.count(x) Returns number of occurrences of x in list

remove() List.remove(x) Removes x from the list


pop() list.pop() Removes the ending element form the list

sort() List.sort() Sorts the elements of the list into ascending


order
reverse() List.reverse() Reverses the sequence of elements in the
list
clear() List.clear() Deletes all elements from the list
List methods
ALIASING AND
CLONING
In Python, aliasing and cloning are concepts related to how objects (especially
mutable ones like lists) are referenced and copied.
• The process of giving another reference to the existing list is called ‘Aliasing’
• x=[10,20,30,40,50]
• y=x
• print(y)
• [10,20,30,40,50]
• If we change the content of x, then y will reflect the same.
• Eg:
• x[1]=55
• x will be [10,55,30,40,50]
• y will be [10,55,30,40,50]
ALIASING
CLONING
• Cloning a list in Python refers to creating an independent copy of an existing
list. This means that changes made to the new list will not affect the original
list, and vice versa
We can implement cloning by using slice operation and copy() function.
• x=[10,20,30,40,50]
• y=x[:] #x is cloned as y
• Print(x) op:[10,20,30,40,50]
• print(y) op:[10,20,30,40,50]
• x[1] = 99 #modifies 1st element in x
• print(x) op:[10,99,30,40,50]
• print(y) op:[10,20,30,40,50]
• We can also use copy function()
• copy means that a new list object is created, but the elements within the
new list are still references to the same objects as in the original list.
EXAMPLE
a = [1, 2, 3, 4, 5]
b = a.copy() # Copying the list
print(b)
OUTPUT: [1,2,3,4,5]
• The copy() method creates a new list with the same elements as the
original.
• It is a shallow copy, meaning it copies the references of nested objects,
not the objects themselves
TUPLE
• Tuple is ordered collection of data which cannot be changed and allows
duplicates, represented in() brackets
• Tuples are similar to lists but the main difference is lists are mutable,
whereas tuples are immutable.
• Creating a Tuple
• We can create a tuple by writing elements separated by commas inside
parentheses().
• The elements can be of same or different kind datatype.
• Eg: tuple = ()
• tuple1= (10,)
• tuple2= (10,20,-30,40.5,’Hyderabad’,’Sky’)
• tuple3= (10,20 ,30)
• tuple4= 10,20,0.9
TUPLE FROM LIST
It is also possible to create a tuple from a list.
This is done by using a tuple function()
Eg: list = [1,2,3,’sky’]
t= tuple(list)
print(t)
#it will display as a tuple
Another way to create a tuple is using range() function that returns a sequence.
t =tuple(range(4,9,2))
Print(t)
(4,6,8) #from 4 to 8 in steps of 2
ACCESSING THE TUPLE
ELEMENTS
Accessing the tuple elements can be done by using indexing or slicing. This is same as a list.
T=(50,60,70,80,90,100)
T[0]
50
T[5]
100
Negative indexing
T[-1]
100
T[-6]
50
BASIC OPERATIONS ON
TUPLES
The basic operations on Tuple are
Finding Length
Concatenation
Repetition
Membership
Example:
• Student = (10, ‘DP’, 50,60,65,61,70)
• Len(student)
• >>7
• #repetition of a tuple:
• Fee=(25000.00,)*4
• Print(fee)
• (25000.0, 25000.0, 25000.0, 25000.0)
• Concatenation of a tuple
• Student1 = student + fee
• Print(student1)
• >>(10, ‘DP’, 50,60,65,61,70, 25000.0, 25000.0, 25000.0, 25000.0)
• Searching whether an element is present in the tuple or not
• Name=‘DP’
• Name in student
• >>True
• Name= ‘PJ’
• Name in student
• >> False
• Name =‘PJ’
• Name not in student
• >>True
Methods
Function Example Description
Len() Len(t) Returns the number of the
elements in the tuple
Min() Min(t) Returns the smallest element in the
tuple
Max() Max(t) Returns the biggest element in the
tuple
Count() Tpl.count() Returns how many times the
element x found in T
Index() t.Index() Returns the first occurence of the
element x in T.
Sorted() Sorted(t) Sorts the elements
Methods
Tuple packing and unpacking
• Packing refers to combining multiple values into a single tuple.
• This is done by simply assigning multiple values to a single variable.
tuple_p = 1,2,3,4
print(tuple_p)
Output: (1,2,3,4)--------------tuple packing

#Tuple unpacking
This is reverse of tuple packing
t=(1,2,3)
a,b,c=t
Print(a,b,c)
1,2,3
Dictionary
• A dictionary represents a group of elements arranged in the form of key-
value pairs.
• The first element in the dictionary is considered as ‘key’, and the immediate
next element is considered as ‘value’
• The key and value are separated by a colon :

• All the key-value pairs in a dictionary are inserted in curly braces { }

• The key must be unique [Immutable],

• Eg: dict = {‘Name’:’SNIST’, ‘Id’ :1, ‘VALUES’ : 1000, 1:100}


Accessing elements in a dictionary

• To access the value associated with a key, we can mention the key name
inside the square braces.
• dict = {‘Name’:”snist”, ‘Id’:1, ‘Salary’ : 1000, 1:100}

• Eg: dict[“Name”] #this will return the value associated with ‘Name’ i.e.,
‘snists’

• dict[‘Salary’]

• >>OP: 1000
• We can also INSERT a new key-value pair into an existing dictionary,
this is done my mentioning the key and assigning a value to it
Eg: dict[‘Dept’] =“AIML”
dict1 #checking the dictionary
OUTPUT: {'Name’: ‘SNIST', 'Salary': 9000, 1: 100, 'Dept': ‘AIML'}
• #the new key-value may add at any place in the dictionary.
• DELETE a KEY
• del dict[1]
• dict
• {'Name’: ‘SNIST', 'Salary': 9000, 'Dept': ‘AIML'}
IN & NOT IN
• To test whether a key is present in the dictionary we use in and not in.
dict ={"name" :"snist","year" : 2025, "subject" :"PP",1:20.5}
print("name" in dict)
OUTPUT: true

• We can use any data types for values, for example, a value can be a number, string, list, tuple or another
dictionary, but the keys should obey the following rules

• KEYS SHOULD BE UNIQUE: It means, duplicate keys are not allowed, if we enter the same key then the old key
will be overwritten and only new key will be available.

• Dict={'Name’: ‘SNIST', 'Salary': 9000, 1: 100, 'Dept': ‘AIML'}

• If we try to add ‘Salary’:1000, then the existing ‘Salary’ will be removed.

• {'Name’: ‘SNIST', 'Salary': 9000, 1: 100, 'Dept': ‘AIML'} #existing

• {'Name’: ‘SNIST', 'Salary': 1000, 1: 100, 'Dept': ‘AIML'} #new


• KEYS SHOULD BE IMMUTABLE TYPE:

• We can use a number, string or tuple as keys since they are immutable, but we cannot use
lists or dictionaries as keys.
METHOD EXAMPLE DESCRIPTION

Clear() d.Clear() Removes all key-value pairs from dictionary’d’

Copy() D1=d.copy() Copies all elements from ‘d’ into a new dictionary ‘d1’

Get() d.get(k) Returns the value associated with key ‘k’, if not it will
return none
items d.Items() Returns an object that contains key-value pairs of ‘d’ the
pairs are stored as tuple in the object

Keys() d.Keys() Returns a sequence of keys from the dictionary ‘d’

Values() d.Values() Returns a sequence of values from the dictionary ‘d’

Update() d.Update(x) Adds all elements from dictionary ‘x’ to ‘d’

Pop() d.Pop(k) Removes the key and its value

You might also like