Python Programming UNIT-1
Python Programming UNIT-1
UNIT – I
INTRODUCTION DATA, EXPRESSIONS, STATEMENTS
Python is a programming language that lets you work quickly and integrate systems
more efficiently.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and
includes new features.
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and
run our programs. There are certain online interpreters like
https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/ that can
be used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from http://python.org/downloads/
# Script Begins
Statement1
Statement2
Statement3
# Script Ends
1
Differences between scripting language and programming language:
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation:
Indentation is one of the greatest features in python
3. It‟s free (open source)
Downloading python and installing python is free and easy
4. It‟s Powerful
• Dynamic typing
• Built-in types and tools
2
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, sciPy)
• Automatic memory management
5. It‟s Portable
• Python runs virtually every major platform used today
• As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It‟s easy to use and learn
• No intermediate compile
• Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
• This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
• Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from http://python.org/downloads/
3
Working with Python
PVM
m.py m.pyc
Without passing python script file to the interpreter, directly execute code to Python
prompt. Once you‟re inside the python interpreter, then you can start.
4
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter
replies 8.
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is
more than 2-4 lines, using the script for coding can help to modify and use the code in
future.
5
Example:
Variables:
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable.
For example −
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables.
For example −
a,b,c = 1,2," “
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Output Variables:
Variables do not need to be declared with any particular type and can even change
type after they have been set.
Output:
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
7
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
An expression is a combination of values, variables, and operators. An expression is
evaluated using assignment operator.
Examples:
y=x + 17
>>> x =10
>>> z = x+20
>>> z
30
>>> x = 10
>>> y = 20
>>> c = x+y
>>> c
30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or
object is an identifier.
Operators: In Python you can implement the following operations using the
corresponding tokens.
Operator Token
add +
subtract -
8
multiply *
Integer Division /
remainder %
and &
or \
Check equality ==
Generator expression:
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
9
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
Conditional expression:
Syntax: true_value if Condition else false_value
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally
two basic statements, the assignment statement and the print statement. Some other
kinds of statements that are if statements, while statements, and for statements
generally called as control flows.
Examples:
>>> x=10
>>> college=" "
Precedence of Operators:
Operator precedence affects how an expression is evaluated.
Example 1:
>>> 3+4*2
11
10
>>> (10+10)*2
40
Example 2:
a = 20
b = 10
c = 15
d=5
e=0
e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/opprec.py
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Comments:
Single-line comments begins with a hash (#) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python,
triple double quote (“ “ “) and single quote(„ „ „)are used for multi-line commenting.
Example:
11
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/comm.py
30
The data stored in memory can be of many types. For example, a student roll number
is stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible
on them and the storage method for each of them.
Int:
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
12
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
13
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
double quotes a r r a y string object is of the type „str‟.
>>> type("name")
<class 'str'>
>>> name=str() ''
>>> name
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0,
• Stop is last index of list
• And for step default is 1
For example, 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print
str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
14
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention
of changing a character in a string.
15
For example:
>>> greeting=' college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can‟t change an
existing string. The best we can do is creating a new string that is a variation on the
original:
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains only numeric characters and
false otherwise.
6. isspace() Returns true if string contains only whitespace characters and
false otherwise.
7. istitle() Returns true if string is properly “titlecased” and false
otherwise.
8. isupper() Returns true if string has at least one cased character and all
cased characters are in uppercase
and false otherwise.
9. replace(old, new [, Replaces all occurrences of old in string with new or at most
max]) max occurrences if max given.
10. split() Splits string according to delimiter str (space if not provided)
and returns list of substrings;
11. count() Occurrence of a string in another string
16
12. find() Finding the index of the first occurrence of a string in another
string
13. swapcase() Converts lowercase letters in a string to uppercase and
viceversa
14. startswith (str, Determines if string or a substring of string (if starting index
beg=0,end=le beg and ending index end are given) starts with substring str;
n(string)) returns true if so and false
otherwise.
Note:
All the string methods will be returning either true or false as the result
isalnum():
isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
string.isalnum()
Example:
>>> string="123alpha"
>>> string.isalnum() True
isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
string.isalpha()
Example:
>>> string="nikhil"
>>> string.isalpha()
True
isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
string.isdigit()
Example:
>>> string="123456789"
>>> string.isdigit() True
islower():
17
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax:
string.islower()
Example:
>>> string="nikhil"
>>> string.islower() True
isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
string.isnumeric()
Example:
>>> string="123456789"
>>> string.isnumeric() True
isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
string.isspace()
Example:
>>> string=" "
>>> string.isspace() True
istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each
word is capital) and false otherwise
Syntax:
string.istitle()
Example:
isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
18
Syntax:
string.isupper()
Example:
>>> string="HELLO"
>>> string.isupper() True
replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.
Syntax:
string.replace()
Example:
>>> string="Nikhil Is Learning"
>>> string.replace('Nikhil','Neha') 'Neha Is Learning'
split()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
string.split()
Example:
>>> string="Nikhil Is Learning"
>>> string.split()
['Nikhil', 'Is', 'Learning']
count()
count() method counts the occurrence of a string in another string
Syntax:
string.count()
Example:
>>> string='Nikhil Is Learning'
>>> string.count('i') 3
find()
find() method is used for finding the index of the first occurrence of a string in another
string
Syntax:
string.find(„string‟)
19
Example:
>>> string="Nikhil Is Learning"
>>> string.find('k')
2
swapcase()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
string.find(„string‟)
Example:
>>> string="HELLO"
>>> string.swapcase() 'hello'
startswith()
Determines if string or a substring of string (if starting index beg and ending index end
are given) starts with substring str; returns true if so and false otherwise.
Syntax:
string.startswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('N') True
endswith()
Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with substring str; returns true if so and false otherwise.
Syntax:
string.endswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('g') True
String module:
It‟s a built-in module and we have to import it before using any of its constants and
classes
Syntax:
import string
20
Note:
help(string) --- gives the information about all the variables, functions, attributes and
classes to be used in string module.
Example:
import string print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
#print(string.whitespace)
print(string.punctuation)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Formatter
It behaves exactly same as str.format() function. This class becomes useful if you want
to subclass it and define your own format string syntax.
Template
This class is used to create a string template for simpler string substitutions Syntax:
from string import Template
Example:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x []
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
22
Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for lists as they
do for strings.
Assuming following input −
L = [' ', 'college', ' !']
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
23
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
• Del()
• Append()
• Extend()
• Insert()
• Pop()
• Remove()
• Reverse()
• Sort()
24
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x=[1, 2, 10, 4, 6, 7]
>>> x.pop()
7
>>> x
[1, 2, 10, 4, 6]
>>> x=[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
25
Reverse: Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
List loop:
Loops are control structures used to repeat a given section of code a certain number of
times or until a particular condition is met.
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
27
[1, 5, 8, 4, 10]
For ex:
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b)
print(a is b)
29
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/alia.py
True
False
True
True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased.
Changes made with one alias affect the other. In the example above, you can see that a
and b refer to the same list after executing the assignment statement b = a.
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to
make a copy of the list itself, not just the reference. This process is sometimes called
cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates
a new list. In this case the slice happens to consist of the whole list.
Example:
a = [81, 82, 83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/clo.py
True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
30
List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of
the list.
Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
# for example, the function below takes a list as an argument and multiplies each
element in the list by 2:
def doubleStuff(List):
""" Overwrite each element in aList with double its value. """
for position in range(len(List)):
List[position] = 2 * List[position]
things = [2, 5, 9]
print(things)
doubleStuff(things)
print(things)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/lipar.py ==
[2, 5, 9]
[4, 10, 18]
List comprehension:
List:
List comprehensions provide a concise way to create lists. Common applications are to
make new lists where each element is the result of some operations applied to each
member of another sequence or inerrable, or to create a subsequence of those elements
that satisfy a certain condition.
>>> list1=[]
>>> for x in range(10):
list1.append(x**2)
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
31
This is also equivalent to
>>> list1=list(map(lambda x:x**2, range(10)))
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
Which is more concise and readable.
>>> list1=[x**2 for x in range(10)]
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
>>> x=()
>>> x
()
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
• Access tuple items
• Change tuple items
• Loop through a tuple
33
• Count ()
• Index ()
• Length ()
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
34
>>> x.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it
was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one
variable at a time. In here, we have assigned tuple 1 with the college information like
college name, year, etc. and another tuple 2 with the values in it like number (1, 2, 3…
7).
For Example,
>>> tup1 = (‘ ‘, 'eng college','2004','cse', 'it','csit');
>>> tup2 = (1,2,3,4,5,6,7);
>>> print(tup1[0])
>>> print(tup2[1:4])
(2, 3, 4)
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
35
Run the above code- It gives name for first tuple while for second tuple it gives
number (2, 3, 4)
def fun():
str = " college"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/tupretval.py
college
20
a=3.14159* r * r
return (c,a)
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
36
Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
a
b
c
Set:
Similarly, to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
>>> x={3*x for x in range(10) if x>5}
>>> x
{24, 18, 27, 21}
37
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
• Key-value pairs
• Unordered
We can construct or create dictionary like:
Example:
>>> dict1 = {"brand":" ","model":"college","year":2004}
>>> dict1
{'brand': ' ', 'model': 'college', 'year': 2004}
Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.
Method Description
fromkeys(seq[, v]) Return a new dictionary with keys from seq and
value equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d
(defaults to None).
items() Return a new view of the dictionary's items (key,
value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if
key is not found. If d is not provided and key is not
found, raises KeyError.
popitem() Remove and return an arbitary item (key, value).
Raises KeyError if the dictionary is empty.
38
setdefault(key[,d]) If key is in the dictionary, return its value. If not,
insert key with a value of d and
return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from
other, overwriting existing keys.
values() Return a new view of the dictionary's values
>>> dict1.values()
dict_values([' ', 'college', 2004])
>>> dict1.items()
dict_items([('brand', '\t'), ('model', 'college'), ('year', 2004)])
college
2004
39
Some more operations like:
• Add/change
• Remove
• Length
• Delete
Add/change values: You can change the value of a specific item by referring to its
key name
11
24
39
4 16
5 25
40
List of Dictionaries:
1 John
2 Smith
3 Andersson
## Modify an entry, This will change the name of customer 2 from Smith to
Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]
## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]
>>> x
{'name': 'John', 'password': '123456'}
41
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:
42