0% found this document useful (0 votes)
4 views91 pages

Unit-3 Python

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, and various operations such as indexing, slicing, and string manipulation. It explains the immutability of strings, the use of operators for concatenation and repetition, and how to perform membership tests. Additionally, it covers string comparison, iteration, and built-in methods for modifying strings.

Uploaded by

ag090pushti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views91 pages

Unit-3 Python

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, and various operations such as indexing, slicing, and string manipulation. It explains the immutability of strings, the use of operators for concatenation and repetition, and how to perform membership tests. Additionally, it covers string comparison, iteration, and built-in methods for modifying strings.

Uploaded by

ag090pushti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000

Department of Computer Science & Engineering

String in Python:

String can be defined as a sequence of characters.

It is surrounded by single quotes, double quotes, or triple quotes:

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.

Syntax of Python String:

str = "Hi Python !"

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.

Creating String in Python

We can make the characters into a string by enclosing them in single or double quotation marks.

str1 = 'Hello Python'

print(str1)

str2 = "Hello Python"

print(str2)

str3 = '''''Triple quotes are generally used for

represent the multiline or

docstring'''

print(str3)

Strings Indexing and Splitting


1
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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.

Access String Characters in Python

We can access the characters in a string in three ways.

Indexing:

Two types of indexing supported in Python.

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'

# access 1st index element

print(str1[1]) # "e"

Backword (Negative) Indexing:

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'

# access 4th last element

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

Department of Computer Science & Engineering

>>> var[-1]

'N'

>>> var[-5]

'Y'

>>> var[-12]

'H'

>>> var[-13]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

if the index goes beyond the range, IndexError is encountered.

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)

It will produce the following output −

Traceback (most recent call last):


File "C:\Users\users\[Link]", line 2, in <module>
var[7]="y"
~~~^^^
TypeError: 'str' object does not support item assignment
.

3
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

Python String Slicing

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.

More general format for slicing the string is:

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)

print ("var[3:8]:", var[3:8])

It will produce the following output –

0 1 2 3 4 5 6 7 8 9 10 11

H E L L O P Y T H O N

var: HELLO PYTHON

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

Department of Computer Science & Engineering

Negative indexes can also be used for slicing.

var="HELLO PYTHON"

print ("var:",var)

print ("var[3:8]:", var[3:8])

print ("var[-9:-4]:", var[-9:-4])

It will produce the following output −


var: HELLO PYTHON
var[3:8]: LO PY
var[-9:-4]: LO PY

0 1 2 3 4 5 6 7 8 9 10 11

H E L L O P Y T H O N

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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.

Slice at Beginning & End

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)

print ("var[0:5]:", var[0:5])

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

It will produce the following output −

var: HELLO PYTHON


5
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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)

print ("var[6:12]:", var[6:12])

print ("var[6:]:", var[6:])

It will produce the following output −

var: HELLO PYTHON


var[6:12]: PYTHON
var[6:]: PYTHON

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)

print ("var[0:12]:", var[0:12])

print ("var[:]:", var[:])

It will produce the following output −

var: HELLO PYTHON


var[0:12]: HELLO PYTHON
var[:]: HELLO PYTHON

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.

Slice with Positive & Negative Indices:

txt="Hello Python"
6
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

print(txt[2:-5])
llo P
You can specify both positive and negative indices at the same time.

Specify Step of the Slicing:

0 1 2 3 4 5 6 7 8 9 10 11

H e L l O P y t h o n

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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

We can even specify a negative step size.

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

Department of Computer Science & Engineering

Python String Operations

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 repetition operator. It concatenates the multiple copies of the same


string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the
specified range.

In It is known as membership operator. It returns true if a particular sub-string is present


in the specified string.

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.

Example of Python operators.

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

Department of Computer Science & Engineering

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

1. Compare Two Strings

We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False.

For example,

str1 = "Hello, world!"

str2 = "I love Python."

str3 = "Hello, world!"

# compare str1 and str2

print(str1 == str2)

# compare str1 and str3

print(str1 == str3)
9
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

In the above example,

str1 and str2 are not equal. Hence, the result is False.

str1 and str3 are equal. Hence, the result is True.

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.

college = "IMSEC, "

city = "Ghaziabad"

# using + operator

result = college + city

print(result)

# Output: IMSEC, Ghaziabad

3. Iterate Through a Python String

We can iterate through a string using a for loop. For example,

course = 'BTECH'

# iterating through greet string

for i in course:

print(course)

Output:

4. Python String Length


10
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

5. String Membership Test


We can test if a substring exists within a string or not, using the keyword in.
To check if a certain phrase or character is present in a string, we can use the keyword in.
print('a' in 'program') # True
We can use it in if statement.
txt = "The Python is a programming language!"
if "Python" in txt:
print("Yes, 'Python' is present.")

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

Python - Modify Strings:


Python has a set of built-in methods that We can use on strings.

11
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

1. The upper() method returns the string in upper case:


a = "Hello, World!"
print([Link]())
2. The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
3. Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print([Link]()) # returns "Hello, World!"
4. The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J"))
Output: Jello, World!

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

Methods of Python String

12
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

There are various string methods present in Python. Here are some of those methods:

Method Description Examples

Returns a copy of the string


capitalize() with its first character
capitalized and the rest
str = "python"
Syntax: lowercased.
[Link]() output=[Link]()
If the first letter of the input
string is a non-alphabet or if print("The resultant string is:",
Parameter it is already a capital letter, output)
This method does not accept then there will be no effect in
any parameters. the output i.e. the original The resultant string is: Python
string is not modified.

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.

Returns the string centered in >>> mystring = "Hello"


a string of length width.
Padding can be done using >>> x = [Link](12,
the specified fillchar (the
Center(width, [fillchar]) "-")
default padding uses an
ASCII space). The original >>> print(x)
string is returned if width is
less than or equal to len(s) ---Hello----

Returns the number of non- >>> mystr = "Hello Python"


overlapping occurrences of
Count(sub, [start], [end]) substring (sub) in the range >>> print([Link]("o"))
[start, end]. Optional
arguments start and end are 2

13
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

interpreted as in slice >>> print([Link]("th"))


notation.
1

>>> print([Link]("l"))

>>> print([Link]("h"))

>>> print([Link]("H"))

>>> print([Link]("hH"))

>>> mystr = 'python!'


Returns an encoded version
>>> print('The string is:',
of the string as a bytes object.
The default encoding is utf-8. mystr)
errors may be given to set a
different error handling The string is: python!
scheme. The possible value
for errors are: >>> print('The encoded

version is: ',


• strict (encoding errors
Encode(encoding = “utf-g”, [Link]("ascii",
raise a UnicodeError)
errors = “strict”)
• ignore "ignore"))
• replace The encoded version is:
• xmlcharrefreplace
b'python!'
• backslashreplace
• any other name >>> print('The encoded
registered via version (with replace) is:',
codecs.register_error()
[Link]("ascii",

"replace"))

14
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

The encoded version (with

replace) is: b'python!'

>>> mystr = "Python"

>>>

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

>>> mystr = "1\t2\t3"

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

Department of Computer Science & Engineering

123

>>> mystring = "Python"

>>>

Returns the lowest index in print([Link]("P"))


the string where
Find(sub, [start], [end]) 0
substring sub is found within
the slice s[start:end]. >>>

print([Link]("on"))

>>> print("{} and

{}".format("Apple",

"Banana"))

Apple and Banana


Performs a string formatting >>> print("{1} and
operation. The string on
which this method is called {0}".format("Apple",
Format(*args, **kwargs)
can contain literal text or
"Banana"))
replacement fields delimited
by braces {}. Banana and Apple

>>> print("{lunch} and

{dinner}".format(lunch="Peas

", dinner="Beans"))

Peas and Beans

Similar to >>> lunch = {"Food":


format(**mapping), except
format_map(mapping) that mapping is used directly "Pizza", "Drink": "Wine"}
and not copied to a
dictionary. >>> print("Lunch: {Food},

16
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

{Drink}".format_map(lunch))

Lunch: Pizza, Wine

>>> class Default(dict):

def __missing__(self,

key):

return key

>>> lunch = {"Drink":

"Wine"}

>>> print("Lunch: {Food},

{Drink}".format_map(Default(

lunch)))

Lunch: Food, Wine

>>> mystr = "HelloPython"

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

>>> mystr = "HelloPython"


Returns True if all characters
Isalnum >>> print([Link]())
in the string are alphanumeric
True

17
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> a = "123"

>>> print([Link]())

True

>>> a= "$*%!!!"

>>> print([Link]())

False

>>> mystr = "HelloPython"

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

>>> mystr = "HelloPython"

>>> print([Link]())

False

Returns True if all characters >>> a="1.23"


Isdecimal()
in the string are decimals
>>> print([Link]())

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

Department of Computer Science & Engineering

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

Returns True if all characters


Islower() >>> c="Python"
in the string are lower case

19
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

Department of Computer Science & Engineering

>>> print([Link]())

False

>>> c="133"

>>> print([Link]())

False

>>> c="Hello Python"

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

Returns True if the string >>> c="Python"


istitle()
follows the rules of a title
>>> print([Link]())

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

Department of Computer Science & Engineering

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"

Returns a left justified >>> b = [Link](12, "_")


ljust(width[,fillchar])
version of the string
>>> print(b)

Hello_______

22
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> a = "Python"
Converts a string into lower
lower() >>> print([Link]())
case
Python

The lstrip() removes >>> a = " Hello "


characters from the left based
lstrip([chars]) on the argument (a string >>> print([Link](), "!")
specifying the set of
characters to be removed). Hello

>>> frm = "SecretCode"

>>> to = "4203040540"

>>> trans_table =

Returns a translation table to [Link](frm,to)


maketrans(x[, y[, z]])
be used in translations
>>> sec_code = "Secret

Code".translate(trans_table)

>>> print(sec_code)

400304 0540

>>> mystr = "Hello-Python"

>>> print([Link]("-

"))
Returns a tuple where the ('Hello', '-', 'Python')
partition(sep) string is parted into three
parts 74

>>>

print([Link]("."))

('Hello-Python', '', '')

23
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> mystr = "Hello Python.

Hello Java. Hello C++."

>>>

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

Hell Python. Hell Java.

Hello C++.

>>> mystr = "Hello-Python"

>>> print([Link]("P"))

Searches the string for a 6


specified value and returns
rfind(sub[, start[,end]]) >>> print([Link]("-"))
the last position of where it
was found 5

>>> print([Link]("z"))

-1

>>> mystr = "Hello-Python"


Searches the string for a
specified value and returns >>> print([Link]("P"))
rindex(sub[, start[,end]])
the last position of where it
6
was found
>>> print([Link]("-"))

24
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> print([Link]("z"))

Traceback (most recent call

last):

File "<pyshell#253>", line

1, in <module>

print([Link]("z"))

ValueError: substring not

found

>>> mystr = "Hello Python"


>>> mystr1 = [Link](20,
Returns the string right
rjust(width[,fillchar]) justified in a string of "-")
length width. >>> print(mystr1)
--------Hello Python

>>> mystr = "Hello Python"

>>>

print([Link]("."))
Returns a tuple where the
rpartition(sep) string is parted into three ('', '', 'Hello Python')
parts
>>> print([Link]("

"))

('Hello', ' ', 'Python')

>>> mystr = "Hello Python"


Splits the string at the
rsplit(sep=None, maxsplit=-1) specified separator, and >>> print([Link]())
returns a list
['Hello', 'Python']

25
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> mystr = "Hello-Python-

Hello"

>>>

print([Link](sep="-",

maxsplit=1))

['Hello-Python', 'Hello']

>>> mystr = "Hello Python"

>>> print([Link](),

"!")

Hello Python !

>>> mystr = "------------

Hello Python-----------"

Returns a right trim version >>> print([Link](), "-


rstrip([chars])
of the string
")

------------Hello Python----

------- -

>>> print([Link](),

"_")

------------Hello Python----

------- _

>>> mystr = "Hello Python"


Splits the string at the
split(sep=None, maxsplit=-1) specified separator, and >>> print([Link]())
returns a list
['Hello', 'Python']

26
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> mystr1="Hello,,Python"

>>> print([Link](","))

['Hello', '', 'Python']

>>> mystr = "Hello:\n\n

Python\r\nJava\nC++\n"

>>>

print([Link]())

['Hello:', '', ' Python',

Splits the string at line breaks 'Java', 'C++']


splitlines([keepends])
and returns a list
>>>

print([Link](keepe

nds=True))

['Hello:\n', '\n', '

Python\r\n', 'Java\n',

'C++\n']

>>> mystr = "Hello Python"

>>>

print([Link]("P"))

Returns true if the string False


startswith(prefix[,start[, end]])
starts with the specified value
>>>

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

Department of Computer Science & Engineering

print([Link]("Hell

"))

True

>>> mystr = "

Hello Python

"

>>> print([Link](),
Returns a trimmed version of
strip([chars]) "!")
the string
Hello Python !

>>> print([Link](), "

")

Hello Python

>>> mystr = "Hello PYthon"


Swaps cases, lower case
swapcase() becomes upper case and vice >>> print([Link]())
versa
hELLO python

>>> mystr = "Hello PYthon"

>>> print([Link]())

Converts the first character of Hello Python


title()
each word to upper case
>>> mystr = "HELLO JAVA"

>>> print([Link]())

Hello Java

translate(table) Returns a translated string >>> frm = "helloPython"

28
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

>>> to = "40250666333"

>>> trans_table =

[Link](frm, to)

>>> secret_code = "Secret

Code".translate(trans_table)

>>> print(secret_code)

S0cr06 C3d0

>>> mystr = "hello Python"


Converts a string into upper
upper() >>> print([Link]())
case
HELLO PYTHON

>>> mystr = "999"

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

Department of Computer Science & Engineering

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

The list of an escape sequence is given below:


Sr. Escape Description Example
Sequence
1. \newline It ignores the new line. print("Python1 \
Python2 \
Python3")
Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")
This escape sequence allows the Output:
programmer to insert a backslash into the \
Python output
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"

30
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

5. \a ASCII Bell print("\a")


6. \b ASCII Backspace(BS) print("Hello \b World")
Output:
Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
8. \n ASCII Linefeed print("Hello \n World!")
Output:
Hello
World!
9. \r ASCII Carriege Return(CR) print("Hello \r World!")
It helps you to create a raw string Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t World!")
Output:
Hello World!
11. \v ASCII Vertical Tab print("Hello \v World!")
Output:
Hello
World!
12. \ooo Character with octal value print("\110\145\154\154\157")
Output:
Hello
13 \xHH Character with hex value. print("\x48\x65\x6c\x6c\x6f")
Output:
Hello

31
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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:

Lists are ordered – Lists remember the order of items inserted.


Accessed by index – Items in a list can be accessed using an index.
Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.
Lists are changeable (mutable) – We can change a list in-place, add new items, and delete or
update existing items.

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

Department of Computer Science & Engineering

# A list of mixed datatypes


L = [ 1, 'abc', 1.23, (3+4j), True]
A list containing zero items is called an empty list and we can create one with empty brackets []

# An empty list
L = []

2. There is one more way to create a list based on existing list, called List comprehension.

The list() Constructor


We can convert other data types to lists using Python’s list() constructor.
Syntax:
L = list()

# Convert a string to a list

L = list('abc')
print(L)
# Prints ['a', 'b', 'c']

# Convert a tuple to a list

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

Department of Computer Science & Engineering

l = ["a", "ab", "c", "ka", "m"]


newlist = []
for x in l:
if "a" in x:
[Link](x)
print(newlist)
['a', 'ab', 'ka']

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

Department of Computer Science & Engineering

Nested List:
A list can contain sublists, which in turn can contain sublists themselves, and so on. This is known as
nested list.

We can use them to arrange data into hierarchical structures.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access List Items by Index:

Each item in a list has an assigned index value. The first item in the list starts at index 0 and ascends
accordingly.

We can access individual items in a list using an index in square brackets.

L = ['red', 'green', 'blue', 'yellow', 'black']

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.

L = ['red', 'green', 'blue', 'yellow', 'black']


print(L[10])
# Triggers IndexError: list index out of range

Output:
IndexError: list index out of range

Negative List Indexing:

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

Department of Computer Science & Engineering

L = ['red', 'green', 'blue', 'yellow', 'black']

print(L[-1])
# Prints black

print(L[-2])
# Prints yellow

Access Nested List Items

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.

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

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

Department of Computer Science & Engineering

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.

The format for list slicing is [start:stop:step].

• start is the index of the list where slicing starts.


• stop is the index of the list where slicing ends.
• step allows us to select nth item within the range start to stop.

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

Department of Computer Science & Engineering

print(my_list[2:])

Output: [3, 4, 5]

my_list = [1, 2, 3, 4, 5]

print(my_list[:2])

Output: [1, 2]

Get the Items at Specified Intervals


my_list = [1, 2, 3, 4, 5]

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]

Change Item Value:

We can replace an existing element with a new value by assigning the new value to the index.

L = ['r', 'g', 'b']

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

Department of Computer Science & Engineering

# Prints ['o', 'g', 'b']

L[-1] = 'v'
print(L)
# Prints ['o', 'g, 'v']

Change a Range of Item Values:

To change the value of items within a specific range, define a list with the new values, and refer to
the range of index numbers where we want to insert the new values:

thislist = ["a", "b", "c", "o", "k", "m"]

thislist[1:3] = ["r", "s"]

print(thislist)

['a', 'r', 's', 'o', 'k', 'm']


['a', 'r', 's', 'o', 'k', 'm']
If we insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:

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

thislist[1:2] = ["r", "s"]

print(thislist)

['a', 'r', 's', 'c']

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

Department of Computer Science & Engineering

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


+
thislist[1:3] = ["r"]

print(thislist)

['a', 'r']

Basic List Operations:

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration

Python Join List:

we can join two or more lists with different functions of Python.


When we join two or more lists together in a Python program, it gives a joined lists. And this process
is called composition or joining of lists.

o Join lists in Python using the join() function and delimiters


o Join a list in Python using the join() function without delimiters
o Join two integers list in Python using map() function
o Join two lists in Python using for loop and append() function
o Join multiple lists in Python using [Link]() method
o Join two lists in Python using (+) plus operator
o Join two lists in Python using (*) multiply or asterisk operator
o Join two lists in Python using extend() function

Join lists in Python using the join() function.

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

Department of Computer Science & Engineering

list1 = ['M', 'o', 'n', 'k', 'y']


print("@".join(list1))

List Replication:

The replication operator * repeats a list a given number of times.

L = ['red']
L=L*3
print(L)
# Prints ['red', 'red', 'red']

Find List Length:

To find the number of items in a list, use len() method.

L = ['red', 'green', 'blue']


print(len(L))
# Prints 3

Check if item exists in a list :

To determine whether a value is or isn’t in a list,we can use in and not in operators with if statement.

# Check for presence


L = ['red', 'green', 'blue']
if 'red' in L:
print('yes')

# Check for absence


L = ['red', 'green', 'blue']
if 'yellow' not in L:
print('yes')

Iterate through a List:

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

Department of Computer Science & Engineering

L = ['red', 'green', 'blue']


for item in L:
print(item)
# Prints red
# Prints green
# Prints blue

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.

# Loop through the list and double each item


L = [1, 2, 3, 4]
for i in range(len(L)):
L[i] = L[i] * 2

print(L)
# Prints [2, 4, 6, 8]

List inbuilt functions:

Add items to a list:

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

Department of Computer Science & Engineering

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.

Equivalent to a[len(a):] = [x].

L = ['red', 'green', 'yellow']


[Link]('blue')
print(L)
# Prints ['red', 'green', 'yellow', 'blue']
Ex 1:

myList = [1, 2, 3, 'a', 'B']


[Link](4)
[Link](5)
[Link](6)
for i in range(7, 9):
[Link](i)
print(myList)

C:\Users\SUDHAKAR DWIVEDI\Desktop>py [Link]


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

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

Example: 1- Create a program to eliminate the List's duplicate items.

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

Department of Computer Science & Engineering

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

Equivalent to a[len(a):] = iterable.

Code:
myList = [1, 2, 3, 'a', 'B']
[Link]([4, 5, 6])
for i in range(7, 11):
[Link](i)
print(myList)

C:\Users\SUDHAKAR DWIVEDI\Desktop>py [Link]


[1, 2, 3, 'a', 'B', 4, 5, 6, 7, 8, 9, 10]

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

Department of Computer Science & Engineering

myList = [1, 2, 3, 'a', 'B']


[Link](3, 4)
[Link](4, 5)
[Link](5, 6)
print(myList)

C:\Users\SUDHAKAR DWIVEDI\Desktop>py [Link]


[1, 2, 3, 4, 5, 6, 'a', 'B']

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.

L = ['red', 'green', 'yellow']


[Link]([1,2,3])
print(L)
# Prints ['red', 'green', 'yellow', 1, 2, 3]

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]

# augmented assignment operator


L = ['red', 'green', 'blue']
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.

Remove items from a list:


45
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

There are several ways to remove items from a list.

• Remove an Item by Index: [Link]([i])

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.

L = ['red', 'green', 'blue']


x = [Link](1)
print(L)
# Prints ['red', 'blue']

# removed item
print(x)
# Prints green

• If we don’t need the removed value, use the del statement.

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

L = ['red', 'green', 'blue']


del L[1]
print(L)
# Prints ['red', 'blue']

• Remove an Item by Value:

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

Department of Computer Science & Engineering

Note : if more than one instance of the given item is present in the list, then this method removes
only the first instance.

L = ['red', 'green', 'blue', 'red']


[Link]('red')
print(L)
# Prints ['green', 'blue', 'red']

• Remove Multiple Items:

To remove more than one items, use the del keyword with a slice index.

L = ['red', 'green', 'blue', 'yellow', 'black']


del L[1:4]
print(L)
# Prints ['red', 'black']

Remove all Items: [Link]()

Use clear() method to remove all items from the list. Equivalent to del a[:].

L = ['red', 'green', 'blue']


[Link]()
print(L)
# Prints []

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.

Python List max() Method Syntax:


max(listname)
Parameter
• listname : Name of list in which we have to find the maximum value.
Returns : It return the maximum value present in the list.

47
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

Code

# maximum of the list

list1 = [103, 675, 321, 782, 200]

# large element in the list

print(max(list1))

Maximum value from the list of characters:

# Declaring a list with random integers.


list1 = ['a', '$', 'e', 'E']

# Store maximum value in a variable


# using Python list max() function.
maxValue = max(list1)

# Printing value stored in maxValue.


print(maxValue)

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.

Python min() Function Syntax


min(a, b, c, …, key=func)
The min() function in Python can take any type of object of similar type and return the smallest
among them. In the case of strings, it returns lexicographically the smallest value.
Parameters
• a, b, c, .. : similar type of data.
• key (optional): A function to customize the sort order
Return: Returns the smallest item.

Code

48
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

# minimum of the list


list1 = [103, 675, 321, 782, 200]
# smallest element in the list
print(min(list1))

9. [Link](x)

Return the number of times x appears in the list.


points = [1, 4, 2, 9, 7, 8, 9, 3, 1]

x = [Link](9)

10. [Link](*, key=None, reverse=False)

Sort the items of the list in place. The sort() method sorts the list ascending by default.

We can also make a function to decide the sorting criteria(s).

Syntax:

[Link](reverse=True|False, key=myFunc)

m=['10','20','30']
[Link](reverse=True)
print(m)

Parameter Values
Parameter Description

reverse Optional. reverse=True will sort the list descending. Default is


reverse=False

key Optional. A function to specify the sorting criteria(s)

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

Department of Computer Science & Engineering

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)

Reverse a List using the Slicing Operator


In this example, the [::-1] slicing operator creates a new list which is the reverse of the my_list.
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)

Reversing a sublist using Slicing


In this example, we are reversing a sublist from index 1 to 3 using [::-1] operator.

Accessing Elements in Reversed Order


In this example, we are traversing the list in the reverse order.
l = [1, 2, 3, 4, 5]
for i in reversed(l):
print(i,end="")
Reversing a list of mixed DataTypes
In this example, we are reversing the list of mixed data types with the reverse() function.
50
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

l = [1, 'a', 2.5, 'c']


print('Original list:', l)
[Link]()
print('Reversed list:', l)

Application : Given a list of numbers, check if the list is a palindrome.


# Python3 program for the
# practical application of reverse()
list_arr = [1, 2, 3, 2, 1]
list_string = list("naman")

# store a copy of list


list2 = list_arr.copy()
list3 = list_string.copy()

# reverse the list


[Link]()
[Link]()

# compare reversed and original list


if list_arr == list2:
print(list_arr, ": Palindrome")
else:
print(list_arr, ": Not Palindrome")

# compare reversed and original list


if list_string == list3:
print(list_string, ": Palindrome")
else:
print(list_string, ": Not Palindrome")

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

Department of Computer Science & Engineering

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

The working of List copy()


Here we will create a Python list and then create a shallow copy using the copy() function in Python.
Then we will append a value to the copied list to check if copying a list using copy() method affects
the original list.

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.

Shallow Copy and Deep Copy


A deep copy is a copy of a list, where we add an element in any of the lists, only that list is
modified.
In list copy() method, changes made to the copied list are not reflected in the original list. The
changes made to one list are not reflected on other lists except for in nested elements (like a list
within a list).

Shallow and Deep copy


Here we will create a list and then create a shallow copy using the assignment operator, list copy()
method, and [Link]() method of the Python copy module.

52
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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)

# all changes are reflected


list2 = list1

# shallow copy - changes to


# nested list is reflected,
# same as [Link](), slicing

list3 = [Link]()

# deep copy - no change is reflected


list4 = [Link](list1)

[Link](5)
list1[1][1] = 999

print("list 1 after modification:\n", list1)


print("list 2 after modification:\n", list2)
print("list 3 after modification:\n", list3)
print("list 4 after modification:\n", list4)

Copy List Using Slicing


Here we are copying the list using the list slicing method [:] and we are appending the ‘a’ to the
new_list. After printing we can see the newly appended character ‘a’ is not appended to the old list.

13. [Link](x[, start[, end]])


Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if
there is no such item.

53
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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.

Built-in Python list methods:

[Link]. Function Description

1 [Link](obj) Appends object obj to list

2 [Link](obj) Returns count of how many times obj occurs in a list

3 [Link](seq) Appends the contents of seq to list

4 [Link](obj) Returns the lowest index in a list that obj appears

5 [Link](index, obj) Inserts object obj into a list at offset index

6 [Link](obj=list[-1]) Removes and returns the last object or obj from the list

7 [Link](obj) Removes object obj from the list

8 [Link]() Reverses objects of the list in place

9 [Link]([func]) Sorts objects of the list, use compare func if given

54
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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.

Tuple has the following characteristics

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

Department of Computer Science & Engineering

# Different types of tuples


# Empty tuple
t = ()
print(t)

# Tuple having integers


t = (1, 2, 3)
print(t)

# tuple with mixed datatypes


t = (1, "Hello", 3.4)
print(t)

# nested tuple
t = ("mouse", [8, 4, 6], (1, 2, 3))
print(t)

t = tuple(('Python', 30, 45.75, [23, 78]))


print(t)

Packing and Unpacking

we can also create tuples without using parentheses:


t=1,2,3
print(type(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

Department of Computer Science & Engineering

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

# packing variables into tuple


tuple1 = 1, 2, "Hello"
# display tuple
print(tuple1)
# Output (1, 2, 'Hello')

print(type(tuple1))
# Output class 'tuple'

# unpacking tuple into variable


i, j, k = tuple1
# printing the variables
print(i, j, k)
# Output 1 2 Hello

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.

Create a Python Tuple With one Element

In Python, creating a tuple with one element is a bit tricky. Having one element within parentheses is
not enough.

We will need a trailing comma to indicate that it is a tuple.

Var1 = (“Hello”) # string


var2 = (“Hello”,) # tuple
print(type(var1))
print(type(var2))

<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

Department of Computer Science & Engineering

Access Python Tuple Elements:

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.

# accessing tuple elements using indexing


letters = (“p”, “r”, “o”, “g”, “r”, “a”, “m”, “I”, “z”)
print(letters[0]) # prints “p”
print(letters[5]) # prints “a”
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\venv\Scripts\[Link]”
“C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject2\[Link]”
p
a

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,

# accessing tuple elements using negative indexing

# accessing tuple elements using negative indexing


letters = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’)
print(letters[-1]) # prints ‘m’
print(letters[-3]) # prints ‘r’

58
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

# elements beginning to 2nd


print(t[:-5]) # prints (‘p’, ‘r’)

# elements 8th to end


print(t[5:]) # prints (‘a’, ‘m’)

# elements beginning to end


print(t[:]) # Prints (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’)

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

Advantages of Tuple over List in Python

Since tuples are quite similar to lists, both of them are used in similar situations.

However, there are certain advantages of implementing a tuple over a list:

• 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

Department of Computer Science & Engineering

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

Different Operations Related to Tuples:

Below are the different operations related to tuples in Python:

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

1. Concatenation of Python Tuples:

To Concatenation of Python Tuples, we will use plus operators(+).

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'programming')

# Concatenating above two

print(tuple1 + tuple2)

2. Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'programming')

tuple3= (tuple1,tuple2)

# Concatenating above two


60
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

print(tuple3)

Output:

((0, 1, 2, 3), ('python', 'programming'))

3. Repetition operator (*)

Like string and list, (*) operator replicates the element of the tuple of specified times.

The syntax of the given operation: Tuple*n

t1=(12, 34, 56)

print( t1*3)

#Output

(12, 34, 56, 12, 34, 56, 12, 34, 56)

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)

print(x > y) #False

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

Department of Computer Science & Engineering

5. Membership Operator (in, not in)

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.

t1=(12, 34, 56, 78, 90)

#membership operator

56 in t1

12 not in t1

#Output

True

False

6. Tuple Slicing:

Tuple slicing is basically used to obtain a range of items.

We perform tuple slicing using the slicing operator.

We can represent the slicing operator in the syntax [start:stop:step].

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:

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

print(tup[1:4])

# prints 2nd to 4th element

(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

Department of Computer Science & Engineering

If we don’t mention the start value the range by default starts from the first term.

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

print(tup[:4])

# prints 1st to 4th element

(22, 3, 45, 4)

Example 3:

If we don’t mention the stop value the range by default ends at the last term.

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

print(tup[4:])

# prints 5th to the last element

(2.4, 2, 56, 890, 1)

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.

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

print(tup[:])

# prints first to the last element

(22, 3, 45, 4, 2.4, 2, 56, 890, 1)

Tuple Functions:

1. The tuple() Function

63
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

We can use the tuple() constructor or function to create a tuple. It basically performs two functions as
follows:

1. Creating an empty tuple if we give no arguments.


2. Creating a tuple with elements if we pass the arguments.

For example:

tup = tuple ((22, 45, 23, 78, 6.89))

print(tup)

(22, 45, 23, 78, 6.89)

tup2 = tuple()

print(tup2)

()

2. The len() Function

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:

tup = (22, 45, 23, 78, 6.89)

print(len(tup))

The count() Function

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

Department of Computer Science & Engineering

For example:

>>>tup = (22, 45, 23, 78, 22, 22, 6.89)

>>> [Link](22)

>>> [Link](54)

The index() Function

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function
basically performs two functions:

• Giving the first occurrence of an element in the tuple.

• Raising an exception if the element mentioned is not found in the tuple.


For example,

Example 1: Finding the index of an element

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](45))

>>> print([Link](890))

#prints the index of elements 45 and 890

The sorted() Function

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

Department of Computer Science & Engineering

For example,

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> sorted(tup)

[1, 2, 2.4, 3, 4, 22, 45, 56, 890]


min(): gives the smallest element in the tuple as an output. Hence, the name is min().

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,

>>> tup = (22, 3, 45, 4, 2, 56, 890, 1)

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

Department of Computer Science & Engineering

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

Department of Computer Science & Engineering

9
16
25

68
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

Dictionary in Python

Dictionaries are used to store data values in key:value pairs.


A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
It provides a way to map pieces of data to each other and allows for quick access to values associated
with keys.
Python dictionaries allow us to associate a value to a unique key, and then to quickly access this value.
It's a good to use whenever we want to find (lookup for) a certain Python object. We can also use lists
for this scope, but they are much slower than dictionaries.
In a dictionary, the keys must be unique and they are stored in an unordered manner.
In the dictionary, a key is separated from values using colon (:) and the values with commas.
d={
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}

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

Department of Computer Science & Engineering

• An empty dictionary is created with curly braces:


Dict = {}
print("Empty Dictionary: ")
print(Dict)
• An empty dictionary can also be created using the built-in function, dict(), with no
arguments:
di= dict()
print(di)

• A dictionary with entries:

Dict = {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}


print(Dict)

Dict = dict({1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'})


print("\nCreate Dictionary by using dict(): ")
print(Dict)

• 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}

• Finally, dictionary keys should be unique.

d={1:2,3:4,1:5,1:7}
print(d)
#{1: 7, 3: 4}

Only the value of the last key is returned.

70
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

D = {'a':'apple' ,'b':'banana', 'c':'cat'}


print(d['z'])
We can prevent this by checking whether key is already available or not by using has_key() function
(or) by using in operator. d.has_key(400) ==> returns 1 if key is available otherwise returns 0

Note : has_key() unction is available only in Python 2 but not in Python 3. Hence compulsory we
have to use in operator.

d={'a':'apple' ,'b':'banana', 'c':'cat'}


if 'b' in d:
print(d['b'])

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

Department of Computer Science & Engineering

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

Updating the Dictionary :


Syntax: d[key]=value

• 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

Department of Computer Science & Engineering

Deleting the elements from Dictionary:


Syntax :
del d[key]
✓ It deletes entry associated with the specified key.
✓ If the key is not available then we will get KeyError.

{200: 'java', 300: 'php'}


Traceback (most recent call last):
File "C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject3\[Link]", line 5, in
<module>
del d[400]
~^^^^^
KeyError: 400
Basic dictionary operations:
Dictionaries are mutable. So , we can perform add/delete/modify/operations on dictionary easily.
d={'a':1,'b':2,'c':4,'d':6}
print(d)
d['e']=7
print(d)
• the new addition will take place at the end of the existing dictionary , since dictionary preserve
the insertion order.
• Dictionary keys can not be changed in place.
In dictionary the operations:
Concatenation : doesn’t work.
Merging: doesn’t work.
Comparison: doesn’t work.
Important functions of Dictionary:
1. dict():
This function is used to create a dictionary.

d=dict()
73
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

Traceback (most recent call last):


File "C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject3\[Link]", line 11,
in <module>
d=dict({[100,"Python"],[200,"Java"],[300,"sql"]})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

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

Department of Computer Science & Engineering

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

Department of Computer Science & Engineering

Important Dictionary Methods:

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

Department of Computer Science & Engineering

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

{200: 'Java', 300: 'sql'}


Traceback (most recent call last):
File "C:\Users\SUDHAKAR DWIVEDI\PycharmProjects\pythonProject3\[Link]",
line 4, in <module>
[Link](400)
KeyError: 400
4. popitem():
It removes an arbitrary item(key-value) from the dictionary and returns it.

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

If the dictionary is empty then we will get KeyError.


d ={}
print([Link]()) #KeyError: 'popitem(): dictionary is empty'

5. keys(): It returns all keys associated with dictionary.

77
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
print([Link]())
for i in [Link]():
print(i)

dict_keys([100, 200, 300])


100
200
300

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)

dict_values(['Python', 'sql', 'Java'])


Python
sql
Java
7. items():
It returns list of tuples representing key-value pairs like as: [(k,v),(k,v),(k,v)]

d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
l= [Link]()
print(l)

dict_items([(100, 'Python'), (300, 'sql'), (200, 'Java')])

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

Department of Computer Science & Engineering

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

8. copy(): This method is used to create exactly duplicate dictionary(cloned copy).

d=dict({(100,"Python"),(200,"Java"),(300,"sql")})
d1=[Link]()
print(d1)
print(d)

{100: 'Python', 200: 'Java', 300: 'sql'}


{100: 'Python', 200: 'Java', 300: 'sql'}

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

Department of Computer Science & Engineering

{100: 'Python', 300: 'sql', 200: 'Java', 400: 'C#'}

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

Dictionary Related Programs


1. Write a program to find number of occurrences of each letter present in the given string.

word=input("Enter any word: ")


d={}
for x in word:
d[x]=[Link](x,0)+1 # we are creating dictionary with the given word ====>
for k,v in [Link]():
print(k,"occurred ",v," times")

Enter any word: programming


p occurred 1 times
r occurred 2 times
o occurred 1 times
g occurred 2 times
a occurred 1 times
m occurred 2 times
i occurred 1 times
n occurred 1 times

word=input("Enter any word: ")


d={}
for x in word:
d[x]=[Link](x,0)+1

80
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

for k,v in sorted([Link]()):


print(k,"occurred ",v," times")

Enter any word: paypal


a occurred 2 times
l occurred 1 times
p occurred 2 times
y occurred 1 times

2. Write a program to find number of occurrences of each vowel present in the given
string.

word=input("Enter any word: ")


vowels={'a','e','i','o','u'}
d={}
for x in word:
if x in vowels:
d[x]=[Link](x,0)+1
for k,v in sorted([Link]()):
print(k,"occurred ",v," times")

Enter any word: queue


e occurred 2 times
u occurred 2 times

81
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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.

Problems of writing the same code repeatedly in the program:

1. Length of the program increases.


2. Readability of the program decreases.
3. No Code Reusability.

How can we resolve this problem?


We have to define these statements as a single unit and we can call that unit any number of times based
on our requirement without rewriting. This unit is nothing but function.
Types of Functions:
Python supports 2 types of functions:
1. Built in Functions
2. User Defined Functions

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

Department of Computer Science & Engineering

2. User Defined Functions:


The functions which are developed by programmer explicitly according to the requirements, are called
user defined functions.
Syntax to create user defined functions:
def function_name(parameters) :
Stmt 1
Stmt 2
---
Stmt n
return value
Note: While creating functions we can use 2 keywords:
1. def (mandatory)
2. return (optional)

Calling a Python Function


After creating a function in Python we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
function name(Parameters)
Eg 1: Write a function to print Hello message

def hello():
print("Hello Good Morning")
hello()
hello()
hello()

Hello Good Morning


Hello Good Morning

83
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

Hello Good Morning

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)

# You will get incorrect output because


# argument is not in order
print("\nCase-2:")
nameAge(27, "X")
Output:
84
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

Department of Computer Science & Engineering

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

II. def hello(msg,name="students"):


print(msg,name)
hello('hello','mr.x')
#hello mr.x

III. def hello(name="students",msg):


print(name,msg)
hello('hello','Mr.x')
# SyntaxError: parameter without a default follows parameter with a default

4. Variable length Parameters:


Sometimes we can pass variable number of arguments to our function, such type of arguments are
called variable length arguments. We can declare a variable length argument with * symbol as follows
def f1(*n): We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.
def sum(*n): # Here, 'n' is a variable length argument. actually variable l
result =0
for x in n:
result = result + x
print(result)
sum(10,20,30,40)
#100

def sum(*n):

86
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

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

Department of Computer Science & Engineering

Hello
None

Write a function to find factorial of given number.


def fact(num):
fact=1
while num>=1:
fact=fact*num
num=num-1
return fact
for i in range(1,5):
print("The Factorial of",i,"is :",fact(i))

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

lambda Function: We can define by using lambda keyword


lambda n:n*n
88
Sudhakar Dwivedi, IMSEC, Ghaziabad
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000

Department of Computer Science & Engineering

Syntax of lambda Function:


lambda argument_list : expression
Note: By using Lambda Functions we can write very concise code so that readability of the program
will be improved.
Lambda Function internally returns expression value and we are not required to write return statement
explicitly.
Write a program to create a Lambda Function to find biggest of given values.
s=lambda a,b:a if a>b else b
print("The Biggest of 10,20 is:",s(10,20))
print("The Biggest of 100,200 is:",s(100,200))

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

Department of Computer Science & Engineering

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

Returning multiple values from a function


In other languages like C, C++ and Java, function can return at most one value. But in Python, a
function can return any number of values.
Eg : Python program to return multiple values at a time using a return statement.
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
a,b,c,d = calc(100,50) # Positional arguments
print(a,b,c,d)
150 50 5000 2.0

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

Department of Computer Science & Engineering

print(x)

150
50
5000
2.0

91
Sudhakar Dwivedi, IMSEC, Ghaziabad

You might also like