Python Unit-1 Notes
Python Unit-1 Notes
UNIT-1
PYTHON FUNDAMENTALS
What is Python?
It is used for:
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.
Python Indentation
Python Comments
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to
think of constants as containers that hold information which cannot be
changed later.
You can think of constants as a bag to store some books which cannot be
replaced once placed inside the bag.
Assigning value to constant in Python
In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, functions, etc which is imported to
the main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Example
x = "John"
# is the same as
x = 'John'
Naming Conventions (Rules to be used while specifying variables in
the program)
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Example
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
Example
x=5
y = 10
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples
above) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Normally, when you create a variable inside a function, that variable is local,
and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside a
function.
Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python has the following data types built-in by default, in these categories:
You can get the data type of any object by using the type() function:
Example
x=5
print(type(x))
Python Numbers
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
int
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
float
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
complex
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
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:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
Python Casting
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.
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
Example
Strings:
Programming Examples:
Write a python program to find area of triangle when 3 sides are given
import math
a=float(input("Enter side1"))
b=float(input("Enter side2"))
c=float(input("Enter side3"))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of Triangle=", area)
Python Operators
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
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:
Bitwise operators are used to compare (binary) numbers. Bitwise operators act
on operands as if they were strings of binary digits. They operate bit by bit,
hence the name.
<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from
shift the left, and let the rightmost bits fall off
Example:
x = 1 + 2 * 3 - 4 / 5 ** 6
The expression is evaluated from left to right, because all the
arithmetic operators are left to right associative operators.
1. Parenthesis
2. Exponentiation (raise to a power)
3. Multiplication, Division (Whichever comes first, that operator will be
evaluated first)
4. Addition and Subtraction (Whichever comes first, that operator will be
evaluated first)
1 + 2 * 3 - 4 / 5 ** 6
1 + 2 * 3 - 4 / 15625
1 + 6 - 4 / 15625
1 + 6 - 0.000256
7 - 0.000256
6.999744
Boolean Values
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and Python returns
the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
The bool() function allows you to evaluate any value, and give
you True or False in return,
Example
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))
Example
Evaluate two variables:
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Most Values are True
Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
In fact, there are not many values that evaluates to False, except empty values,
such as (), [], {}, "", the number 0, and the value None. And of course the
value False evaluates to False.
Example
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Example
Check if an object is an integer or not:
x = 200
print(isinstance(x, int))
Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a
variable name, function name or any other identifier.
The above keywords may get altered in different versions of Python. Some
extra might get added or some might be removed. You can always get the list
of keywords in your current version by typing the following in the prompt.
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
if statement
Syntax:
if expression:
statements
Example
if statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".
Indentation
Example
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Programming example:
if-else statement
It is basically used when we have 2 choices or alternatives.
Syntax:
if expression:
statements
else:
statements
Write a Python program to find the largest of 2 numbers
if a>b:
print("a is largest")
else:
print("b is largest")
if num%2==0:
print("Number is even")
else:
print("Number is odd")
if age>=18:
print("Eligible to Vote")
else:
elif
The elif keyword is python’s way of saying "if the previous conditions were not
true, then try this condition". elif statement is basically used when we have
more than 2 choices or alternatives.
else:
print("All the three numbers are equal")
num=float(input("Enter a number"))
if num>0:
print("Number is positive")
elif num<0:
print("Number is negative")
else:
print("Number is zero")
if marks<0 or marks>100:
print("Invalid marks")
elif marks<=35:
print("Grade F")
elif marks>=36 and marks<=50:
print("Grade E")
print("Grade D")
print("Grade C")
print("Grade B")
print("Grade A")
else:
print("Grade O - Outstanding")
Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.
Example
Example
a=2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
nested-if
if a>b:
if a>c:
else:
else:
if b>c:
else:
Programming Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example
a = 33
b = 200
if b > a:
pass
while loop
for loop
while Loop
With the while loop we can execute a set of statements as long as a condition
is true.
Syntax:
while expression/condition:
while i<=n:
print(i)
i=i+1
i=1
while i<=n:
print(i)
i=i+2
i=2
while i<=n:
print(i)
i=i+2
i=1
while i<=n:
print(i**2)
i=i+1
i=1
while i<=n:
print(i**3)
i=i+1
i=1
sum=0
while i<=n:
sum=sum+i
i=i+1
i=1
sum=0
while i<=n:
sum=sum+(i**2)
i=i+1
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Syntax:
for val in sequence:
Example
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
Example
for x in range(6):
print(x)
Example
Example
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
for x in adj:
for y in fruits:
print(x, y)
pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
break Statement
With the break statement we can stop the loop before it has looped through
all the items: break statement is used to end or terminate the loop when
certain condition is met.
Example1:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Example2:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
continue Statement
With the continue statement we can stop the current iteration of the loop, and
continue with the next: continue statement is used to end the current iteration
of the loop.
Example
for i in range(1,n+1,1):
print(i)
for i in range(1,n+1,2):
print(i)
for i in range(2,n+1,2):
print(i)
for i in range(1,n+1,1):
print(i**2)
for i in range(1,n+1,1):
print(i**3)
sum=0
for i in range(1,n+1,1):
sum=sum+i
sum=0
for i in range(1,n+1,1):
sum=sum+(i**2)
print("Sum of squares of natural numbers=", sum)
Functions
Functions also called as modules can be defined as set of statements
which are written to achieve a specific task.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
def func_name(parameters):
statements:
Example
def my_function( ):
print("Hello REVA")
Calling a Function
Example
def my_function( ):
print("Hello REVA ")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Kumar")
my_function("Shiva")
my_function("Sachin")
my_function("Praveen")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
def my_function(*students):
print("The youngest student is " + students[1])
my_function("shiva", "vishnu", "krishna")
You can also send arguments with the key = value syntax.
Example
def my_function(student3, student2, student1):
print("The youngest student is " + student3)
my_function(student1 = "shiva", student2 = "vishnu", student3 = "krishna")
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example
def my_function(**student):
print("His Last name is " + student[“lname”])
my_function(fname=”shiva”, lname=”kumar”)
Arbitrary Kword Arguments are often shortened to **kwargs in Python
documentations.
Example
def my_function(country = "India"):
print("I am from " + country)
my_function("England")
my_function("USA")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
return statement
To let a function return a value, use the return statement:
Example1:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example2:
def add(a,b):
return a+b
res=add(10,20)
print("Sum is",res)
pass Statement
function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.
Example
def myfunction( ):
pass
Note: Python does not have built-in support for Arrays, but Python Lists can
be used instead.
Write a python program to find the sum of 2 numbers using user
defined function
We can write the program by using 2 methods, in first method we can read the
input from the user, in second method we will create the function with
parameters and when we invoke or call the function, we can call the function
with the values.
First Method:
Program:
def sum():
a=int(input('Enter first number'))
b=int(input('Enter second number'))
s=a+b
print('sum of 2 numbers is',s)
sum()
Second Method:
Program:
def sum(a,b):
s=a+b
print('sum of 2 numbers is',s)
sum(30,60)
Write a Python program to perform basic arithmetic operations
using user defined functions
def arithmetic(a,b):
sum=a+b
sub=a-b
mult=a*b
div=a/b
mod=a%b
exp=a**b
print('Sum of 2 numbers is',sum)
print('Subtraction of 2 numbers is',sub)
print('multiplication of 2 numbers is',mult)
print('division of 2 numbers is',div)
print('modulus of 2 numbers is',mod)
print('Exponentiation is',exp)
arithmetic(10,3)
def sum1(a,b):
c=a+b
print('sum of 2 integers is',c)
sum1(10,20)
def sum2(a,b):
c=a+b
print('sum of 2 floats is',c)
sum2(10.5,20.5)
Write a Python program to read and print the name, SRN and
Marks obtained by the student using user defined functions
def sdetails():
name=input("Enter the Student Name")
SRN=input("Enter the Student SRN")
marks=float(input("Enter the Marks obtained by the student"))
print("Student Name is",name)
print("Student SRN is",SRN)
print("Marks obtained is",marks)
sdetails()
There are four collection data types in the Python programming language:
List
List is indexed.
list_name=[e1,e2,……..en]
Where in e1,e2,…. So on are the elements being inserted into the list.
Example
Create a List:
Access Items
Example
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
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.
Example
Note: The search will start at index 2 (included) and end at index 5 (not
included).
By leaving out the start value, the range will start at the first item:
Example
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
Specify negative indexes if you want to start the search from the end of the
list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
You can loop through the list items by using a for loop:
Example
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
Example: You want to create a list of all the fruits that has the letter "a" in the
name.
Without list comprehension you will have to write a for statement with a
conditional test inside:
Example
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
print(newlist)
Example
List Length
To determine how many items a list has, use the len() function:
Example
Add Items
To add an item to the end of the list, use the append() method:
Example
Example
Remove Item
Example
Example
The pop() method removes the specified index, (or the last item if index is not
specified):
L1 = ["apple", "banana", "cherry"]
L1.pop()
print(L1)
Example
Example
Example
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().
Example
Example
There are several ways to join, or concatenate, two or more lists in Python.
Another way to join two lists are by appending all the items from list2 into
list1, one by one:
Example
for x in list2:
list1.append(x)
print(list1)
Or you can use the extend() method, which purpose is to add elements from
one list to another list:
Example
list1.extend(list2)
print(list1)
Example
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first element with the specified value
Program:
List1” is a list that contains the “N” different SRN of students read using a user defined
function with the help of input(). SRN of “M” more students are to be appended or
inserted into “List1” at the appropriate place and also return the index of the SRN
entered by user.
print(list1)
print(list1)
Tuple is indexed.
tuple_name=(e1,e2,……..en)
Where in e1,e2,…. So on are the elements being inserted into the tuple.
Example
Create a Tuple:
You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
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 tuple with the
specified items.
Example
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the
tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Example
print(x)
You can loop through the tuple items by using a for loop.
Example
Example
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Example
Example
Example
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of
where it was found
Set
Set is unindexed.
set_name={e1,e2,……..en}
Where in e1,e2,…. So on are the elements being inserted into the set.
Example
Create a Set:
Note: Sets are unordered, so you cannot be sure in which order the items will
appear.
Access Items
But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
Example
for x in S1:
print(x)
Example
Check if "banana" is present in the set:
print("banana" in S1)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example
S1.add("orange")
print(S1)
Example
print(S1)
Example
print(len(S1))
Remove Item
Example
S1.remove("banana")
print(S1)
Note: If the item to remove does not exist, remove() will raise an error.
Example
S1.discard("banana")
print(S1)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.
Example
x = S1.pop()
print(x)
print(S1)
Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.
Example
S1.clear()
print(S1)
Example
del S1
print(S1)
Join Two Sets
You can use the union() method that returns a new set containing all items
from both sets, or the update() method that inserts all the items from one set
into another:
Example
The union() method returns a new set with all items from both sets:
set3 = set1.union(set2)
print(set3)
Example
set1.update(set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
There are other methods that joins two sets and keeps ONLY the duplicates, or
NEVER the duplicates, check the full list of set methods in the bottom of this
page.
Example
Using the set() constructor to make a set:
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
update() Update the set with the union of this set and
others
Dictionary
Dictionary is indexed.
In Python dictionary is written with curly or flower brackets and they have
keys and value pairs.
dictionary_name={key1:value1,key2:value2,……..keyn:valuen}
Example
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(D1)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Example
D1["model"]
There is also a method called get() that will give you the same result:
Example
D1.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D1["year"] = 2018
Example
for x in D1:
print(x)
Example
for x in D1:
print(D1[x])
Example
You can also use the values() method to return values of a dictionary:
for x in D1.values():
print(x)
Example
Loop through both keys and values, by using the items() method:
for x, y in D1.items():
print(x, y)
Example
Dictionary Length
Example
print(len(D1)
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D1["color"] = "red"
print(D1)
Removing Items
Example
The pop() method removes the item with the specified key name:
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D1.pop("model")
print(D1)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D1.popitem()
print(D1)
Example
The del keyword removes the item with the specified key name:
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del D1["model"]
print(D1)
Example
Example
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D1.clear()
print(D1)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also
be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Example
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D2 = D1.copy()
print(D2)
Another way to make a copy is to use the built-in function dict().
Example
D1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
D2 = dict(D1)
print(D2)
Nested Dictionaries
Example
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Or, if you want to nest three dictionaries that already exists as dictionaries:
Example
Create three dictionaries, then create one dictionary that will contain the other
three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault( Returns the value of the specified key. If the key does not exist: insert
) the key, with the specified value