Unit-3 Python
Unit-3 Python
String in Python:
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are
also called the collection of Unicode characters.
In Python, a string is a sequence of characters enclosed within single quotes (”), double quotes (" "),
or triple quotes (""" """). It is a fundamental data type used to represent and manipulate textual data.
Strings in Python are immutable, which means that once a string is created, it cannot be modified.
However, we can perform various operations on strings to extract information, manipulate their
content, and create new strings.
Because strings are seen as collections of characters, Python does not allow the character data-type;
instead, a single character written as "p" is interpreted as a string of length 1.
We can make the characters into a string by enclosing them in single or double quotation marks.
print(str1)
print(str2)
docstring'''
print(str3)
The slice operator [] is used to access the string’s individual characters. However, we may use
Python’s: (colon) operator to extract the substring from the given text.
Indexing:
1. Forward Indexing
2. Backword Indexing
Forward Indexing: One way is to treat strings as a list and use index values. The indexes of string
start from 0 to length-1.
For example,
str1 = 'hello'
print(str1[1]) # "e"
One of the unique features of Python sequence types (and therefore a string object) it has a negative
indexing scheme also. The Backword indexes of string starts from -1 to -length.
For Example
str1 = 'hello'
print(str1[-4]) # "e"
A positive indexing scheme is used where the index increments from left to right.
In case of negative indexing, the character at the end has -1 index and the index decrements from
right to left, as a result the first character H has -12 index.
2
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> var[-1]
'N'
>>> var[-5]
'Y'
>>> var[-12]
'H'
>>> var[-13]
In Python, string is an immutable object. The object is immutable if it cannot be modified in-place,
once stored in a certain memory location.
We can retrieve any character from the string with the help of its index, but we cannot replace it with
another character
var="HELLO PYTHON"
var[7]="y"
print (var)
3
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Python defines ":" as string slicing operator. It returns a substring from the original string. Its
general usage is –
substr=var[x:y]
The ":" operator needs two integer operands (both of which may be omitted)
The first operand x is the index of the first character of the desired slice. The second operand y is the
index of the character next to the last in the desired string.
So var(x:y] separates characters from xth position to (y-1)th position from the original string.
String[start:end:step]
• start: the beginning index of the slice, it will include the element at this index unless it is the
same as stop, defaults to 0, i.e. the first index. If it’s negative, it means to start n items from the
end.
• stop: the ending index of the slice, it does not include the element at this index, defaults to the
length of the sequence being sliced, that is, up to and including the end.
•
• step: the amount by which the index increases, defaults to 1. If it’s negative, we’re slicing over
the iterable in reverse.
var="HELLO PYTHON"
print ("var:",var)
0 1 2 3 4 5 6 7 8 9 10 11
H E L L O P Y T H O N
var[3:8]: LO PY
4
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
var="HELLO PYTHON"
print ("var:",var)
0 1 2 3 4 5 6 7 8 9 10 11
H E L L O P Y T H O N
Both the operands for Python's Slice operator are optional. The first operand defaults to zero,
which means if we do not give the first operand, the slice starts of character at 0th index, i.e. the
first character. It slices the leftmost substring up to "y-1" characters.
Omitting the start index starts the slice from the index 0. Meaning, string[:stop] is equivalent
to S[0:stop].
var="HELLO PYTHON"
print ("var:",var)
Whereas, omitting the stop index extends the slice to the end of the string.
Meaning, String[start:] is equivalent to String[start:len(String)]
print ("var[:5]:", var[:5])
var[0:5]: HELLO
var[:5]: HELLO
Similarly, y operand is also optional. By default, it is "-1", which means the string will be sliced from
the xth position up to the end of string.
var="HELLO PYTHON"
print ("var:",var)
Naturally, if both the operands are not used, the slice will be equal to the original string. That's
because "x" is 0, and "y" is the last index+1 (or -1) by default.
var="HELLO PYTHON"
print ("var:",var)
The left operand must be smaller than the operand on right, for getting a substring of the
original string. Python doesn't raise any error, if the left operand is greater, but returns a null
string.
txt="Hello Python"
6
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(txt[2:-5])
llo P
You can specify both positive and negative indices at the same time.
0 1 2 3 4 5 6 7 8 9 10 11
H e L l O P y t h o n
We can specify the step of the slicing using step parameter. The step parameter is optional and by
default 1.
txt="Hello Python"
print(txt[2:8:2])
loP
txt="Hello Python"
print(txt[8:2:-2])
tPo
Reverse a String:
We can reverse a string by omitting both start and stop indices and specifying a step as -1.
nohtyP olleH
7
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
There are many operations that can be performed with strings which makes it one of the most used
data types in Python.
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
str = "Hello"
str1 = " world"
print(str*3)
print(str+str1)
print(str[4])
8
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(str[2:4])
print('w' in str)
print('wo' not in str1)
print(r'C://python37')
print("The string str : %s"%(str))
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False.
For example,
print(str1 == str2)
print(str1 == str3)
9
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
str1 and str2 are not equal. Hence, the result is False.
In Python, we can join (concatenate) two or more strings using the + operator.
city = "Ghaziabad"
# using + operator
print(result)
course = 'BTECH'
for i in course:
print(course)
Output:
In Python, we use the len() method to find the length of a string. For example,
language = 'Pyhton'
# count length of greet string
print(len(language))
# Output: 6
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
print('at' not in 'apple') #False
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
txt = "The Python is a programming language!"
if "java" not in txt:
print("Yes, 'Java' is not present.")
11
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
The strip() method removes any whitespace from the beginning or the end:
5. The split() method returns a list where the text between the specified separator becomes
the list items.
The split() method returns a list where the text between the specified separator becomes the list
items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!'] a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
12
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
There are various string methods present in Python. Here are some of those methods:
Casefold()
>>> mystring = "hello
Syntax: [Link]() PYTHON"
Returns a casefolded copy of
Parameters: The casefold()
the string. Casefolded strings >>> print([Link]())
method doesn’t take any
may be used for caseless
parameters.
matching. hello python
Return value: Returns the
case folded string the string
converted to lower case.
13
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> print([Link]("l"))
>>> print([Link]("h"))
>>> print([Link]("H"))
>>> print([Link]("hH"))
"replace"))
14
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>>
print([Link]("y"))
Returns True if the string
endswith(suffix, [start], [end]) ends with the specified suffix, False
otherwise it returns False.
>>>
print([Link]("hon"))
True
>>> print(mystr)
123
>>>
print([Link]())
Returns a copy of the string 123
where all tab characters are
replaced by one or more >>>
Expandtabs(tabsize=8)
spaces, depending on the
print([Link](tabsi
current column and the given
tab size. ze=15))
12
>>>
print([Link](tabsi
ze=2))
15
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
123
>>>
print([Link]("on"))
{}".format("Apple",
"Banana"))
{dinner}".format(lunch="Peas
", dinner="Beans"))
16
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
{Drink}".format_map(lunch))
def __missing__(self,
key):
return key
"Wine"}
{Drink}".format_map(Default(
lunch)))
>>> print([Link]("P"))
5
Searches the string for a
specified value and returns >>>
Index(sub, [start], [end])
the position of where it was
print([Link]("hon"))
found
8
>>> print([Link]("o"))
17
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> a = "123"
>>> print([Link]())
True
>>> a= "$*%!!!"
>>> print([Link]())
False
>>> print([Link]())
True
>>> a = "123"
Returns True if all characters
Isalpha() in the string are in the >>> print([Link]())
alphabet
False
>>> a= "$*%!!!"
>>> print([Link]())
False
>>> print([Link]())
False
False
>>> c = u"\u00B2"
>>> print([Link]())
18
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
False
>>> c="133"
>>> print([Link]())
True
>>> c="133"
>>> print([Link]())
True
>>> c = u"\u00B2"
Returns True if all characters
Isdigit() >>> print([Link]())
in the string are digits
True
>>> a="1.23"
>>> print([Link]())
False
>>> c="133"
>>> print([Link]())
False
>>> c="_user_123"
Returns True if the string is
isidentifier() >>> print([Link]())
an identifier
True
>>> c="Python"
>>> print([Link]())
True
19
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> print([Link]())
False
>>> c="_user_123"
>>> print([Link]())
True
>>> print([Link]())
False
>>> c="133"
>>> print([Link]())
True
>>> c="_user_123"
Returns True if all characters
Isnumeric() >>> print([Link]())
in the string are numeric
False
>>> c="Python"
>>> print([Link]())
False
>>> c="133"
>>> print([Link]())
True
Returns True if all characters
isprintable() >>> c="_user_123"
in the string are printable
>>> print([Link]())
True
>>> c="\t"
20
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> print([Link]())
False
>>> c="133"
>>> print([Link]())
False
>>> print([Link]())
False
Returns True if all characters
isspace() 73
in the string are whitespaces
>>> c="Hello"
>>> print([Link]())
False
>>> c="\t"
>>> print([Link]())
True
>>> c="133"
>>> print([Link]())
False
True
>>> c="\t"
>>> print([Link]())
21
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
False
>>> c="Python"
>>> print([Link]())
False
>>> c="PYHTON"
Returns True if all characters
isupper() >>> print([Link]())
in the string are upper case
True
>>> c="\t"
>>> print([Link]())
False
>>> a ="-"
>>> print([Link]("123"))
1-2-3
The string join() method >>> a="Hello Python"
returns a string by joining all
join(iterable) the elements of an iterable >>> a="**"
(list, string, tuple), separated
by the given separator. >>> print([Link]("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
>>> a="Hello"
Hello_______
22
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> a = "Python"
Converts a string into lower
lower() >>> print([Link]())
case
Python
>>> to = "4203040540"
>>> trans_table =
Code".translate(trans_table)
>>> print(sec_code)
400304 0540
>>> print([Link]("-
"))
Returns a tuple where the ('Hello', '-', 'Python')
partition(sep) string is parted into three
parts 74
>>>
print([Link]("."))
23
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>>
print([Link]("Hello",
"Bye"))
Returns a string where a Bye Python. Bye Java. Bye
replace(old, new[,count]) specified value is replaced
with a specified value C++.
>>>
print([Link]("Hello",
"Hell", 2))
Hello C++.
>>> print([Link]("P"))
>>> print([Link]("z"))
-1
24
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> print([Link]("z"))
last):
1, in <module>
print([Link]("z"))
found
>>>
print([Link]("."))
Returns a tuple where the
rpartition(sep) string is parted into three ('', '', 'Hello Python')
parts
>>> print([Link]("
"))
25
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Hello"
>>>
print([Link](sep="-",
maxsplit=1))
['Hello-Python', 'Hello']
>>> print([Link](),
"!")
Hello Python !
Hello Python-----------"
------------Hello Python----
------- -
>>> print([Link](),
"_")
------------Hello Python----
------- _
26
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> mystr1="Hello,,Python"
>>> print([Link](","))
Python\r\nJava\nC++\n"
>>>
print([Link]())
print([Link](keepe
nds=True))
Python\r\n', 'Java\n',
'C++\n']
>>>
print([Link]("P"))
print([Link]("H"))
True
>>>
27
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print([Link]("Hell
"))
True
Hello Python
"
>>> print([Link](),
Returns a trimmed version of
strip([chars]) "!")
the string
Hello Python !
")
Hello Python
>>> print([Link]())
>>> print([Link]())
Hello Java
28
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
>>> to = "40250666333"
>>> trans_table =
[Link](frm, to)
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
>>> print([Link](9))
Fills the string with a 000000999
zfill(width) specified number of 0 values
at the beginning >>> mystr = "-40"
>>> print([Link](5))
-0040
Escape Sequence:
Suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can
be written in single quotes or double quotes but it will raise the SyntaxError as it contains both
single and double-quotes.
Example:
str = "They said, "Hello what's going on?""
29
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(str)
SyntaxError: unterminated string literal (detected at line 1)
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We can
apply the same as in the double quotes.
print('''''They said, "What's there?"''')
# escaping single quotes
print('They said, "What\'s going on?"')
# escaping double quotes
print("They said, \"What's going on?\"")
Output:
''They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"
30
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
31
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Python List
A list is a sequence of values (similar to an array in other programming languages but more versatile)
The values in a list are called items or sometimes elements.
A list in Python is a sequence data type used for storing a comma-separated collection of objects in a
single variable.
Lists are always ordered and can contain different types of objects (strings, integers, booleans, etc.).
Since they are mutable data types, lists are a good choice for dynamic data (that may be added or
removed over time).
The important properties of Python lists are as follows:
Create a List
There are several ways to create a new list;
1. The simplest is to enclose the values in square brackets []
Syntax:
L= [ ]
# A list of integers
L = [1, 2, 3]
# A list of strings
L = ['red', 'green', 'blue']
The items of a list don’t have to be the same type. The following list contains an integer, a string, a
float, a complex number, and a boolean.
32
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
# An empty list
L = []
2. There is one more way to create a list based on existing list, called List comprehension.
L = list('abc')
print(L)
# Prints ['a', 'b', 'c']
L = list((1, 2, 3))
print(L)
# Prints [1, 2, 3]
33
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
With list comprehension you can do all that with only one line of code:
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 iterable, or to create a subsequence of those elements that satisfy a certain condition.
A list comprehension consists of brackets containing an expression followed by a for clause, then
zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in
the context of the for and if clauses which follow it. For example, this list comp combines the
elements of two lists if they are not equal:
s=[]
for x in range(10):
[Link](x**2)
print(s)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can obtain the same result with: s = [x**2 for x in range(10)]
print([(x, y) for x in [1,2,3] for y in [3,1,4] if x != y])
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
34
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Nested List:
A list can contain sublists, which in turn can contain sublists themselves, and so on. This is known as
nested list.
Each item in a list has an assigned index value. The first item in the list starts at index 0 and ascends
accordingly.
print(L[0])
# Prints red
print(L[2])
# Prints blue
Output:
red
blue
Python will raise an IndexError error, if we use an index that exceeds the number of items in our list.
Output:
IndexError: list index out of range
We can access a list by negative indexing as well. Negative indexes count backward from the end of
the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.
35
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(L[-1])
# Prints black
print(L[-2])
# Prints yellow
We can access individual items in a nested list using multiple indexes. The first index determines
which list to use, and the second indicates the value within that list.
print(L[2][2])
# Prints ['eee', 'fff']
print(L[2][2][0])
# Prints eee
36
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Slicing a List:
We can slice a list in order to access a range of elements in it. One method is to utilize the colon as a
simple slicing operator (:).
The slice operator allows us to specify where to begin slicing, where to stop slicing, and what step to
take. List slicing creates a new list from an old one.
Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Output: [3, 4]
my_list = [1, 2, 3, 4, 5]
37
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(my_list[2:])
Output: [3, 4, 5]
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])
Output: [1, 2]
print(my_list[::2])
Output: [1, 3, 5]
If you want the indexing to start from the last item, you can use negative sign -.
my_list = [1, 2, 3, 4, 5]
print(my_list[::-2])
Output: [5, 3, 1]
If you want the items from one position to another, you can mention them from start to stop.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4:2])
Output : [2, 4]
We can replace an existing element with a new value by assigning the new value to the index.
L[0] = 'o'
print(L)
38
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
L[-1] = 'v'
print(L)
# Prints ['o', 'g, 'v']
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 we want to insert the new values:
print(thislist)
print(thislist)
Note: The length of the list will change when the number of items inserted does not match the
number of items replaced.
If we insert less items than we replace, the new items will be inserted where we specified, and
the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:
39
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(thislist)
['a', 'r']
A join() function is used to join an iterable list to another list, separated by specified delimiters such
as comma, symbols, a hyphen, etc.
Syntax
1. str_name.join( iterable)
40
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
List Replication:
L = ['red']
L=L*3
print(L)
# Prints ['red', 'red', 'red']
To determine whether a value is or isn’t in a list,we can use in and not in operators with if statement.
The most common way to iterate through a list is with a for loop.
41
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
This works well if we only need to read the items of the list. But if we want to update them, we need
the indexes. A common way to do that is to combine the range() and len() functions.
print(L)
# Prints [2, 4, 6, 8]
1. len()
The built-in len() method to find the length of a list. The len() method accepts a sequence or a
collection as an argument and returns the number of elements present in the sequence or collection
Return the number of items in a list:
mylist = ["a", "b, "c"]
x = len(mylist)
print(“length of list is=”,x)
2. append() - [Link](x)
42
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
The append() method adds elements at the end of the list. This method can only add a single element
at a time. We can use the append() method inside a loop to add multiple elements.
Ex 2:
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
[Link](input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Code
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
43
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
list2 = []
for i in list1:
if i not in list2:
[Link](i)
print(list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
3. extend() - [Link](iterable)
The extend() method adds more than one element at the end of the list. Although it can add more
than one element, unlike append(), it adds them at the end of the list like append().
Code:
myList = [1, 2, 3, 'a', 'B']
[Link]([4, 5, 6])
for i in range(7, 11):
[Link](i)
print(myList)
4. insert() - [Link](i, x)
The insert() method can add an element at a given position in the list. Thus, unlike append(), it can
add elements at any position, but like append(), it can add only one element at a time. This method
takes two arguments. The first argument specifies the position, and the second argument specifies the
element to be inserted.
The first argument is the index of the element before which to insert, so [Link](0, x) inserts at the
front of the list, and [Link](len(a), x) is equivalent to [Link](x).
Note that all of the values in the list after the inserted value will be moved down one index.
44
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
5. Combine Lists
We can merge one list into another by using extend() method. It takes a list as an argument and
appends all of the elements.
Alternatively, We can use the concatenation operator + or the augmented assignment operator +=
# concatenation operator
L = ['red', 'green', 'blue']
L = L + [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]
6. remove() - [Link](x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such
[Link] the first occurrence of the same element is removed in the case of multiple occurrences.
If we know the index of the item we want, we can use pop() method. It Remove the item at the
given position in the list, and return it. If no index is specified, [Link]() removes and returns the last
item in the list. (The square brackets around the i in the method signature denote that the parameter is
optional.
If no index is specified, pop() removes and returns the last item in the list.
# removed item
print(x)
# Prints green
Here is a way to remove an item from a list given its index instead of its value: the del statement.
This differs from the pop() method which returns a value. The del statement can also be used to
remove slices from a list or clear the entire list
If ’re not sure where the item is in the list, use remove() method to delete it by value.
L = ['red', 'green', 'blue']
[Link]('red')
print(L)
# Prints ['green', 'blue']
46
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Note : if more than one instance of the given item is present in the list, then this method removes
only the first instance.
To remove more than one items, use the del keyword with a slice index.
Use clear() method to remove all items from the list. Equivalent to del a[:].
7. Max( )
It returns the maximum element of the list. In this case of character values the max value is
determined on the basis of their ASCII values.
47
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Code
print(max(list1))
In this case of character values the max value is determined on the basis of their ASCII values. For
example ASCII value of ‘e’ is 101 and ‘E’ is 69 therefore ‘e’ is larger.
8. Min( )
Python min() function returns the smallest of the values or the smallest item in an iterable passed as
its parameter.
Code
48
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
9. [Link](x)
x = [Link](9)
Sort the items of the list in place. The sort() method sorts the list ascending by default.
Syntax:
[Link](reverse=True|False, key=myFunc)
m=['10','20','30']
[Link](reverse=True)
print(m)
Parameter Values
Parameter Description
11. [Link]()
Python List reverse() is an inbuilt method in the Python programming language that reverses
objects of the List in place i.e. it doesn’t use any extra space but it just modifies the original list.
Python List reverse() Syntax
49
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Syntax: list_name.reverse()
Parameters: There are no parameters.
Returns: The reverse() method does not return any value but reverses the given object from the
list.
For Example :
list1 = [1, 2, 3, 4, 1, 2, 6]
[Link]()
print(list1)
# a list of characters
list2 = ['a', 'b', 'c', 'd', 'a', 'a']
[Link]()
print(list2)
12. [Link]()
Return a shallow copy of the list. Equivalent to a[:]. List Copy() function in Python is used to create
a copy of a list. There are two main ways to create a copy of the list Shallow copy and Deep copy.
Python List copy() function is used to create a copy of a list, which can be used to work and it will
not affect the values in the original list. This gives freedom to manipulate data without worrying
about data loss.
List copy() Method Syntax
51
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
[Link]()
Parameters
• The copy() method doesn’t take any parameters
Returns: Returns a shallow copy of a list. A shallow copy means any modification in the new list
won’t be reflected in the original list.
l = [1,2,3]
m = [Link]()
print('Copied List:', m)
l1 = [ 1, 2, 3, 4 ]
l2 = [Link]()
print ("The new list created is : " + str(l2))
[Link](5)
print ("The new list after adding new element : " + str(l2))
print ("The old list after adding new element to new list : " + str(l1))
Output:
The new list created is : [1, 2, 3, 4]
The new list after adding new element : [1, 2, 3, 4, 5]
The old list after adding new element to new list : [1, 2, 3, 4]
Note: A shallow copy means if we modify any of the nested list elements, changes are reflected in
both lists as they point to the same reference.
52
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
We also create a deep copy using deepcopy() in Python. Then we will make changes to the original
list and see if the other lists are affected or not.
mport copy
# Initializing list
list1 = [ 1, [2, 3] , 4 ]
print("list 1 before modification:\n", list1)
list3 = [Link]()
[Link](5)
list1[1][1] = 999
53
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
The optional arguments start and end are interpreted as in the slice notation and are used to limit the
search to a particular subsequence of the list. The returned index is computed relative to the
beginning of the full sequence rather than the start argument.
6 [Link](obj=list[-1]) Removes and returns the last object or obj from the list
54
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Tuple Manipulation
In Python, tuple is also a kind of container which can store list of any kind of values.
• Tuple is built-in sequence data type.
• Store Multiple Values.
• It can have multiple data types.
• All the vales are comma separated and enclosed within ().
• Tuple is an immutable data type which means we can not change any value of tuple.
• Tuple is a sequence like string and list but the difference is that list is mutable whereas string
and tuple are immutable.
• In case of single item in tuple, it should also followed by comma.
• A Sequence without parenthesis is treated as tuple by default.
Ordered: Tuples are part of sequence data types, which means they hold the order of the data
insertion. It maintains the index value for each item.
Unchangeable: Tuples are unchangeable, which means that we cannot add or delete items to the
tuple after creation.
Heterogeneous: Tuples are a sequence of data of different data types (like integer, float, list, string,
etc;) and can be accessed through indexing and slicing.
Contains Duplicates: Tuples can contain duplicates, which means they can have items with the
same value.
Creating a Tuple
We can create a tuple using the two ways
• Using parenthesis (): A tuple is created by enclosing comma-separated items inside rounded
brackets. The parentheses are optional.
• Using a tuple() constructor: Create a tuple by passing the comma-separated items inside the
tuple().
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
A tuple can have any number of items and they may be of different types (integer, float, list, string,
etc.).
55
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
# nested tuple
t = ("mouse", [8, 4, 6], (1, 2, 3))
print(t)
<class 'tuple'>
A tuple can also be created without using a tuple() constructor or enclosing the items inside the
parentheses. It is called the variable “Packing.”
In Python, we can create a tuple by packing a group of variables. Packing can be used when we want
to collect multiple values in a single variable. Generally, this operation is referred to as tuple
packing.
Similarly, we can unpack the items by just assigning the tuple items to the same number of variables.
This process is called “Unpacking.
56
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
In case we assign fewer variables than the number of items in the tuple, we will get the value error
with the message too many values to unpack
print(type(tuple1))
# Output class 'tuple'
The statement t = 12345, 54321, ’hello!’ is an example of tuple packing: the values 12345, 54321
and ’hello!’ are packed together in a tuple.
x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-
hand side. Sequence unpacking requires that there are as many variables on the left side of the equals
sign as there are elements in the sequence.
Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
In Python, creating a tuple with one element is a bit tricky. Having one element within parentheses is
not enough.
<class ‘str’>
<class ‘tuple’>
57
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index
0.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. For example,
58
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\venv\Scripts\[Link]”
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\[Link]”
m
r
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :.
# accessing tuple elements using slicing
t = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’)
# elements 2nd to 4th index
print(t[1:4]) # prints (‘r’, ‘o’, ‘g’)
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\venv\Scripts\[Link]”
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\[Link]”
(‘r’, ‘o’, ‘g’)
(‘p’, ‘r’)
(‘a’, ‘m’)
(‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’)
Since tuples are quite similar to lists, both of them are used in similar situations.
• We generally use tuples for heterogeneous (different) data types and lists for homogeneous
(similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with a list. So there is a
slight performance boost.
59
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
• Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this
is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.
1. Concatenation
2. Nesting
3. Repetition
4. Slicing
5. Deleting
6. Finding the length
7. Multiple Data Types with tuples
8. Conversion of lists to tuples
9. Tuples in a Loop
tuple1 = (0, 1, 2, 3)
print(tuple1 + tuple2)
tuple1 = (0, 1, 2, 3)
tuple3= (tuple1,tuple2)
print(tuple3)
Output:
Like string and list, (*) operator replicates the element of the tuple of specified times.
print( t1*3)
#Output
4. Comparison Operator
Python offers standard comparison operators like ==,<, >, != to compare two lists.
For comparison, two tuples must-have elements of comparable types, otherwise, it will
generate an error.
Python gives the result of comparison operators as True or False and moreover, it compares
tuple list element by element.
It compares the first element if they are the same then will move to the next, and so on.
x = (1,2,2)
y = (1,2,3)
because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2
is less than three -lexicographically -)
61
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
The membership operator checks whether an element exists in the given tuple sequence.
in: Return True if an element exists in the given tuple; False otherwise
not in: Return True if an element does not exist in the given tuple; False otherwise.
#membership operator
56 in t1
12 not in t1
#Output
True
False
6. Tuple Slicing:
It is not necessary to mention the ‘step’ part. The compiler considers it 1 by default if we do
not mention the step part.
Example 1:
print(tup[1:4])
(3, 45, 4)
Example 2:
62
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
If we don’t mention the start value the range by default starts from the first term.
print(tup[:4])
(22, 3, 45, 4)
Example 3:
If we don’t mention the stop value the range by default ends at the last term.
print(tup[4:])
Example 4:
If we don’t mention both the start and stop value the range by default starts from the first term
and ends at the last term.
print(tup[:])
Tuple Functions:
63
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
We can use the tuple() constructor or function to create a tuple. It basically performs two functions as
follows:
For example:
print(tup)
tup2 = tuple()
print(tup2)
()
This function returns the number of elements present in a tuple. Moreover, it is necessary to provide a
tuple to the len() function.
For example:
print(len(tup))
This function will help us to fund the number of times an element is present in the tuple.
Furthermore, we have to mention the element whose count we need to find, inside the count
function.
64
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
For example:
>>> [Link](22)
>>> [Link](54)
The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function
basically performs two functions:
>>> print([Link](45))
>>> print([Link](890))
This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not make
any changes to the original tuple.
65
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
For example,
>>> sorted(tup)
For example,
max(): gives the largest element in the tuple as an output. Hence, the name is max().
For example,
>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
>>> max(tup)
890
For example,
>>> sum(tup)
1023
Tuple Assignment:
Assignment of tuple is a useful feature in Python. It allows a tuple of variables on the left side of the
assignment operator to be assigned respective values from a tuple on the right side. The number of
variables on the left should be same as the number of elements in the tuple.
(num1,num2) = (10,20)
print(num1)
66
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(num2)
record = ( "Pooja",40,"CS")
(name,rollNo,subject) = record
print(name)
print(rollNo)
print(subject)
(a,b,c,d) = (5,6,8)
Output:
ValueError: not enough values to unpack (expected 4, got 3)
10
20
Pooja
40
CS
If there is an expression on the right side then first that expression is evaluated and finally the result
is assigned to the tuple.
Tuple Comprehension:
Tuple Comprehension is not supported by Python.
t= ( x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.
t= ( x**2 for x in range(1,6))
print(type(t))
for x in t:
print(x)
<class 'generator'>
1
4
67
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
9
16
25
68
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Dictionary in Python
Note: As of Python version 3.7, dictionaries are ordered based on insertion, but this is not the case
in previous versions.
Creating a Dictionary
The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be
changed at runtime such as int, string, tuple, etc. The values can be of any type.
Individual pairs will be separated by a comma(“,”) and the whole thing will be enclosed in curly
braces({...}).
69
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
• using dict(), in which we supply keys and values as a keyword argument list or as a list of
tuples:
d=dict([(1,2),(3,4),(5,6)])
print(d)
#{1: 2, 3: 4, 5: 6}
d={1:2,3:4,1:5,1:7}
print(d)
#{1: 7, 3: 4}
70
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Accessing a Dictionary
The values in a dictionary can be accessed by passing the associated key name in
a dictionary[key] syntax:
Dict = {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
print(Dict)
print(Dict[3])
Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
Facebook
If the specified key is not available then we will get KeyError
Note : has_key() unction is available only in Python 2 but not in Python 3. Hence compulsory we
have to use in operator.
Write a program to enter name and percentage marks in a dictionary and display information
on the screen.
rec={}
n=int(input("Enter number of students: "))
i=1
71
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
while i <= n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of Marks")
for x in rec:
print("\t",x,"\t",rec[x])
• If the key is not available then a new entry will be added to the dictionary with the specified
key-value pair.
• If the key is already available then old value will be replaced with new value.
d={100:"python",200:"java",300:"php"}
print(d)
d[400]="sql"
print(d)
d[100]="html"
print(d)
Output:
{100: 'python', 200: 'java', 300: 'php'}
{100: 'python', 200: 'java', 300: 'php', 400: 'sql'}
{100: 'html', 200: 'java', 300: 'php', 400: 'sql'}
72
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
d=dict()
73
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(d)
d=dict({100:"Python",200:"Java"})
print(d)
d=dict([(100,"Python"),(200,"Java"),(300,"sql")])
print(d)
d=dict(((100,"Python"),(200,"Java"),(300,"sql")))
print(d)
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print(d)
d=dict({[100,"Python"],[200,"Java"],[300,"sql"]})
print(d)
{}
{100: 'Python', 200: 'Java'}
{100: 'Python', 200: 'Java', 300: 'sql'}
{100: 'Python', 200: 'Java', 300: 'sql'}
{200: 'Java', 300: 'sql', 100: 'Python'}
Note:
Compulsory internally we need to take tuple only is acceptable. If you take list it gives the
above specified error.
2. len(d)
Returns the number of items in the dictionary d.
d=dict()
print(len(d))
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print(len(d))
Output:
0
3
3. sorted(d):
it returns the sorted list of keys in dictionary d.
74
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
d={'c':1,'a':2,'d':4,'b':6}
print(sorted(d))
['a', 'b', 'c', 'd']
4. reversed(d):
used to reversing dict/keys/values.
d={'a':1,'b':2,'d':4,'c':6}
for k,v in reversed([Link]()):
print(k,v)
5. min(d):
returns minimum key in the dictionary.
d={'c':10,'b':2,'a':4,'d':6}
print('Minimum key is=',min(d))
Minimum key is= a
6. max(d):
returns maximum key in the dictionary.
d={'c':10,'b':2,'a':4,'d':6}
print('Maximum key is=',max(d))
Maximum key is= d
7. any(d):
returns true if any key of dictionary is true.
d={1:10,0:2,0:4,0:6}
print(any(d)) # True
8. all(d):
returns true if all key of dictionary is true.
d={1:10,5:2,9:4,10:6}
print(all(d))
# True
9. sum(d):
returns sum of all the keys if they are numbers.
d={1:10,5:2,9:4,10:6}
print(sum(d))
25
75
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
1. clear():
To remove all elements from the dictionary.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
[Link]()
print(d)
Output:
{}
2. get():
✓ To get the value associated with the key.
✓ Two forms of get() method is available in Python.
I. [Link](key)
If the key is available then returns the corresponding value otherwise returns None.
It wont raise any error.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link](100))
print([Link](500))
Python
None
II. [Link](key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link](100,'html'))
print([Link](500,'html'))
Python
Html
3. pop():
Syntax : [Link](key)
76
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
✓ It removes the entry associated with the specified key and returns the corresponding
value.
✓ If the specified key is not available then we will get KeyError.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
[Link](100)
print(d)
[Link](400)
print(d)
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link]())
print(d)
print([Link]())
print(d)
(300, 'sql')
{100: 'Python', 200: 'Java'}
(200, 'Java')
{100: 'Python'}
77
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link]())
for i in [Link]():
print(i)
6. values():
It returns all values associated with the dictionary.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link]())
for i in [Link]():
print(i)
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
l= [Link]()
print(l)
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
for k,v in [Link]():
print(k,'-',v)
100 - Python
300 - sql
200 – Java
• while iterating though dictionary using a for loop, if we wish to keep track of index of
key value pairs that is being referred to , we can use built in enumerate() function.
78
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
d={1:2,3:4,5:6}
for i , (k,v) in enumerate([Link]()):
print('indiex of value ',v,'is:',i)
indiex of value 2 is: 0
indiex of value 4 is: 1
indiex of value 6 is: 2
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
d1=[Link]()
print(d1)
print(d)
9. setdefault():
Syntax : [Link](k,v)
✓ If the key is already available then this function returns the corresponding value.
✓ If the key is not available then the specified key-value will be added as new item to
the dictionary.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link](100,'C++'))
print(d)
print([Link](400,'C#'))
print(d)
Python
{100: 'Python', 300: 'sql', 200: 'Java'}
C#
79
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
10. update():
Syntax : [Link](x)
All items present in the dictionary x will be added to dictionary d.
d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
d1=dict({(400,"C++"),(500,"C#")})
[Link](d1)
print(d)
{300: 'sql', 100: 'Python', 200: 'Java', 500: 'C#', 400: 'C++'}
80
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
2. Write a program to find number of occurrences of each vowel present in the given
string.
81
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Function in Python
If a group of statements is repeatedly required then we can define these statements as a single unit and
we can call that unit any number of times based on our requirement without rewriting.
Python Functions is a block of statements that perform the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
Functions are a convenient way to divide our code into useful blocks, allowing us to order our code,
make it more readable, reuse it and save some time. Also functions are a key way to define interfaces
so programmers can share their code.
This unit is nothing but function. The main advantage of functions is code Reusability.
Note: In other languages functions are known as methods, procedures, subroutines etc.
1. Built in Functions:
The functions which are coming along with Python software automatically, are called built in functions
or pre-defined functions.
Eg: id(), type() ,input() ,eval() etc..
82
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
def hello():
print("Hello Good Morning")
hello()
hello()
hello()
83
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Parameters:
Parameters are inputs to the function. If a function contains parameters, then at the time of calling,
compulsory we should provide values, otherwise we will get error.
Types of Parameters in Python:
Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following 4 types of function arguments.
• Positional Parameters
• Keyword Parameters
• Default Parameters
• Variable length Parameters
1. Positional Parameters:
In the case of positional arguments, number of arguments must be same. In the case of positional
arguments, order of the arguments is important.
# You will get correct output because
def nameAge(name,age):
print('Hi, I am',name)
print('My age is', age)
nameAge('X',27)
# argument is given in order
print("Case-1:")
nameAge("X", 27)
Case-1:
Hi, I am X
My age is 27
Case-2:
Hi, I am 27
My age is X
2. Keyword (i.e., Parameter name) Parameters:
In the case of keyword arguments, order of the arguments is not important. In the case of keyword
arguments, number of arguments must be same.
I.
def calc(a,b): # keyword arguments
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
t = calc(100, b = 50) # It is perfectly valid
for x in t:
print(x)
150
50
5000
2.0
def calc(a,b): # keyword arguments.
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
t = calc(b = 50,100) # It is invalid, because positional argument follows keyword argument
for x in t:
print(x)
85
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
3. Default Parameters:
We can define default value for the arguments. If we are not passing any argument, then default values
by default will be considered. After default arguments we should not take normal arguments. (i.e.,
Default arguments you need to take at last).
I. def hello(msg,name="students"):
print(msg,name)
hello('hello')
#hello students
def sum(*n):
86
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
result =0
for x in n:
result = result + x
print(result)
sum(10,20)
#30
return statement
Function can take input values as parameters and executes the logic, and returns output to the caller
with return statement. Python function can return any number of values at a time by using a return
statement.
Default return value of any python function is None.
Write a function to accept 2 numbers as input and return sum.
def add(x,y):
return x+y
result=add(100,200)
print("The sum is",result)
print("The sum is",add(100,200))
The sum is 30
The sum is 300
Note : If we are not writing return statement then default return value is None.
def f1():
print("Hello")
a=f1()
print(a)
87
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Hello
None
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24
Anonymous Functions:
Anonymous Functions Sometimes we can declare a function without any name, such type of nameless
functions are called anonymous functions or lambda functions. The main purpose of anonymous
function is just for instant use(i.e., for one time usage).
Normal Function: We can define by using def keyword.
def squareIt(n):
return n*n
Recursive Functions:
A function that calls itself is known as Recursive Function.
Eg: factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1 =6
factorial(n)= n*factorial(n-1)
The main advantages of recursive functions are:
1. We can reduce length of the code and improves readability.
2. We can solve complex problems very easily. For example, Towers of Hanoi, Ackerman's
Problem etc.,
Write a Python Function to find factorial of given number with recursion.
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
89
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print("Factorial of 0 is :",factorial(0))
print("Factorial of 4 is :",factorial(4))
print("Factorial of 5 is :",factorial(5))
print("Factorial of 40 is :",factorial(40))
Alternate Way :
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
t = calc(100,50)
for x in t:
90
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
print(x)
150
50
5000
2.0
91
Sudhakar Dwivedi, IMSEC, Ghaziabad