You are on page 1of 75

Unit-II Sem-V Sub-Python

Control Statements:

Python Break, Continue and Pass statement

Python break statement

It is sometimes desirable to skip some statements inside the loop or terminate the
loop immediately without checking the test expression. In such cases we can
use break statements in Python. The break statement allows you to exit a loop from
any point within its body, bypassing its normal termination expression.

As seen in the above image, when the break statement is encountered inside a loop,
the loop is immediately terminated, and program control resumes at the next
statement following the loop.
break statement in while loop

n=1

while True:

print (n)

n+=1

if n==5:

break

print("After Break")

output:

After Break

In the above program, when n==5, the break statement executed and immediately
terminated the while loop and the program control resumes at the next statement.
break statement in for loop

for str in "Python":

if str == "t":

break

print(str)

print("Exit from loop")

output:

Exit from loop

Python continue statement

Continue statement works like break but instead of forcing termination, it forces
the next iteration of the loop to take place and skipping the rest of the code.

continue statement in while loop

n=0

while n < 5:

n+=1

if n==3:

continue

print (n)

print("Loop Over")
output:

Loop Over

In the above program, we can see in the output the 3 is missing. It is because when
n==3 the loop encounter the continue statement and control go back to start of the
loop.

continue statement in for loop

n=0

for n in range(5):

n+=1

if n==3:

continue

print(n)

print("Loop Over")

output

Loop Over
In the above program, we can see in the output the 3 is missing. It is because when
n==3 the loop encounter the continue statement and control go back to start of the
loop.

Python Pass Statement

In Python, the pass keyword is used to execute nothing; it means, when we don't
want to execute code, the pass can be used to execute empty. It is the same as the
name refers to. It just makes the control to pass by without executing any code. If we
want to bypass any code pass statement can be used.

It is beneficial when a statement is required syntactically, but we want we don't want


to execute or execute it later. The difference between the comments and pass is that,
comments are entirely ignored by the Python interpreter, where the pass statement
is not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we
will execute in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

# pass is just a placeholder for

# we will adde functionality later.

values = {'P', 'y', 't', 'h','o','n'}

for val in values:

pass

Example - 2:

for i in [1,2,3,4,5]:

if(i==4):

pass

print("This is pass block",i)

print(i)
Output:

This is pass block 4

String Manipulation

String:

String – String represents group of characters. Strings are enclosed in double quotes
or single quotes. The str data type represents a String.

Ex:- “Hello”, “Python”, ‘Rahul’

str1 = “Python”

Creating String

Single Quotes

str1 = ‘Python’

Double quotes

str2 = “Python”

Triple Single Quotes – This is useful to create strings which span into several lines.

str3 = ‘‘‘ Hello Guys

Please Subscribe

Python’’’
Triple Double Quotes – This is useful to create strings which span into several lines.

str4 = “““Hello Guys

Please Subscribe

Python ”””

Double Quote inside Single Quotes

str5 = ‘Hello “Python” How are you’

Single Quote inside Double quotes

str6 = “Hello ‘Python’ How are you”

Using Escape Characters

str7 = “Hello \nHow are You ?”

Raw String – Row string is used to nullify the effect of escape characters.

str8 = r“Hello \nHow are You ?”


Repetition Operator

Repetition operator is used to repeat the string for several times. It is denoted by *

Ex:-

“$” * 7

str1 = “Geeky Shows ”

str1 * 5

Concatenation Operator

Concatenation operator is used to join two string. It is denoted by +

Ex:-

“Geeky” + “Shows”

str1 = “Geeky ”

str2 = “Shows”

str1 + str2
Comparing String

str1 = “GeekyShows”

str2 = “GeekyShows”

result = str1 == str2

str1 = “GeekyShows”

str2 = “Python”

result = str1 == str2

str1 = “A”

str2 = “B”

result = str1 < str2


Slicing String:

Slicing on String can be used to retrieve a piece of the string. Slicing is useful to
retrieve a range of elements.

Syntax:-

new_string_name = string_name[start:stop:stepsize]

start – It represents starting point. By default its 0

stop – It represents ending point.

stepsize – It represents step interval. By default It is 1

If start and stop are not specified then slicing is done from 0th to n-1th elements.

Start and Stop can be negative number.


String Functions::

1) upper ( ) – This method is used to convert all character of a string into


uppercase.

Syntax:- string.upper( )

print("****** Upper Function ******")

name = "python"

str1 = name.upper()

print(name)

print(str1)

2) lower ( ) – This method is used to convert all character of a string into


lowercase.

Syntax:- string.lower( )

print("****** Lower Function ******")

name = "PYTHON"

str1 = name.lower()

print(name)

print(str1)

3) swapcase ( ) – This method is used to convert all lower case character into
uppercase and vice versa.

Syntax:- string.swapcase ( )

print("****** Swapcase Function ******")

name = "python"

str1 = name.swapcase()

print(name)

print(str1)
4) title ( ) – This method is used to convert the string in such that each word in
string will start with a capital letter and remaining will be small letter.

Syntax:- string.title ( )

print("****** Title Function ******")

name = "hello python how are you"

str1 = name.title()

print(name)

print(str1)

5) isupper ( ) – This method is used to test whether given string is in upper case
or not, it returns True if string contains at least one letter and all characters are
in upper case else returns False.

Syntax:- string.isupper( )

print("****** isupper Function ******")

name = "PYTHON"

str1 = name.isupper()

print(name)

print(str1)

6) islower ( ) – This method is used to test whether given string is in lower case
or not, it returns True if string contains at least one letter and all characters are
in lower case else returns False.

Syntax:- string.islower( )

print("****** islower Function ******")

name = "python"

str1 = name.islower()

print(name)

print(str1)
7) istitle ( ) – This method is used to test whether given string is in title format or
not, it returns True if string contains at least one letter and each word of the
string starts with a capital letter else returns False.

Syntax:- string.istitle( )

print("****** istitle Function ******")

name = "Hello Python How Are You"

str1 = name.istitle()

print(name)

print(str1)

8) isdigit ( ) – This method returns True if the string contains only numeric digits
(0 to 9) else returns False.

Syntax:- string.isdigit()

print("****** isdigit Function ******")

name = "342343"

str1 = name.isdigit()

print(name)

print(str1)

9) isalpha ( ) – This method returns True if the string has at least one character
and all are alphabets ( A to Z and a to z) else returns False

Syntax:- string.isalpha()

print("****** isalpha Function ******")

name = "PYthon"

str1 = name.isalpha()

print(name)

print(str1)
10) isalnum ( ) – This method returns True if the string has at least one
character and all characters in the string are alphanumeric (A to Z, a to z and 0
to 9) else returns False

Syntax:- string.isalnum()

print("****** isalnum Function ******")

name = "PYthon2343"

str1 = name.isalnum()

print(name)

print(str1)

11) isspace ( ) – This method returns True if the string contains only space
else returns False.

Syntax:- string.isspace()

print("****** isspace Function ******")

name = " "

str1 = name.isspace()

print(name)

print(str1)

12) lstrip ( ) – This method is used to remove the space which are at left
side of the string.

Syntax:- string.lstrip()

print("****** lstrip Function ******")

name = " Python"

str1 = name.lstrip()

print(name)

print(str1)
13) rstrip ( ) – This method is used to remove the space which are at right
side of the string.

Syntax:- string.rstrip()

print("****** rstrip Function ******")

name = "Python "

str1 = name.rstrip()

print(name)

print(str1)

14) strip ( ) – This method is used to remove the space from the both side
of the string.

Syntax:- string.strip()

print("****** strip Function ******")

name = " Python "

str1 = name.strip()

print(name)

print(str1)

15) replace ( ) – This method is used to replace a sub string in a string with
another sub string. Syntax:- string.replace(old, new)

print("****** replace Function ******")

name = "Python"

old = "Py"

new = "New"

str1 = name.replace(old, new)

print(name)

print(str1)
16) split ( ) – This method is used to split/break a string into pieces. These
pieces returns as a list.

Syntax:- string.split(‘separator’)

print("****** split Function ******")

name = "Hello-how-are-you"

str1 = name.split('-')

print(name)

print(str1)

17) join ( ) – This method is used to join strings into one string.

Syntax:- “separator”.join(string_list)

print("****** join Function ******")

name = ('Hello', 'How', 'Are', 'You')

str1 = "_".join(name)

print(name)

print(str1)

18) startswith ( ) – This method is used to check whether a string is


starting with a substring or not. It returns True if the string starts with
specified sub string.

Syntax:- string.startswith(‘specified_string’)

print("****** startswith Function ******")

name = "Hi How are you"

str1 = name.startswith('Hi')

print(name)

print(str1)
19) endswith ( ) – This method is used to check whether a string is ending
with a substring or not. It returns True if the string ends with specified sub
string.

Syntax:- string.startswith(‘specified_string’)

print("****** endswith Function ******")

name = "Thank you Bye"

str1 = name.endswith('Bye')

print(name)

print(str1)
String Methods::

1) center()

The center() method returns a string which is padded with the specified character.

The syntax of center() method is: string.center(width[, fillchar])

center() Parameters

The center() method takes two arguments:

width - length of the string with padded characters

fillchar (optional) - padding character

The fillchar argument is optional. If it's not provided, space is taken as default
argument.

Return Value from center()

The center() method returns a string padded with specified fillchar. It doesn't modify
the original string.

Example 1: center() Method With Default fillchar

string = "Python is awesome"

new_string = string.center(24)

print("Centered String: ", new_string)

Output:

Centered String: Python is awesome


Example 2: center() Method With * fillchar

string = "Python is awesome"

new_string = string.center(24, '*')

print("Centered String: ", new_string)

Output:

Centered String: ***Python is awesome****

2) zfill()

The zfill() method returns a copy of the string with '0' characters padded to the left.

The syntax of zfill() in Python is: str.zfill(width)

zfill() Parameter

zfill() takes a single character width.

The width specifies the length of the returned string from zfill() with 0 digits filled to
the left.

Return Value from zfill()

zfill() returns a copy of the string with 0 filled to the left. The length of the returned
string depends on the width provided.

Suppose, the initial length of the string is 10. And, the width is specified 15. In this
case, zfill() returns a copy of the string with five '0' digits filled to the left.

Suppose, the initial length of the string is 10. And, the width is specified 8. In this
case, zfill() doesn't fill '0' digits to the left and returns a copy of the original string.
The length of the returned string in this case will be 10.
Example 1: How zfill() works in Python?

text = "program is fun"

print(text.zfill(15))

print(text.zfill(20))

print(text.zfill(10))

Output

0program is fun

000000program is fun

program is fun

If a string starts with the sign prefix ('+', '-'), 0 digits are filled after the first sign prefix
character.

Example 2: How zfill() works with Sign Prefix?

number = "-290"

print(number.zfill(8))

number = "+290"

print(number.zfill(8))

text = "--random+text"

print(text.zfill(20))
Output

-0000290

+0000290

-0000000-random+text

3) isidentifier()

The isidentifier() method returns True if the string is a valid identifier in Python. If not,
it returns False.

The syntax of isidentifier() is: string.isidentifier()

isidentifier() Paramters

The isidentifier() method doesn't take any parameters.

Return Value from isidentifier()

The isidentifier() method returns:

True if the string is a valid identifier

False if the string is not a invalid identifier

Example 1: How isidentifier() works?

str = 'Python'

print(str.isidentifier())

str = 'Py thon'

print(str.isidentifier())
str = '22Python'

print(str.isidentifier())

str = ''

print(str.isidentifier())

Output

True

False

False

False

Example 2: More Example of isidentifier()

• str = 'root33'

if str.isidentifier() == True:

print(str, 'is a valid identifier.')

else:

print(str, 'is not a valid identifier.')

• str = '33root'

if str.isidentifier() == True:

print(str, 'is a valid identifier.')

else:

print(str, 'is not a valid identifier.')


• str = 'root 33'

if str.isidentifier() == True:

print(str, 'is a valid identifier.')

else:

print(str, 'is not a valid identifier.')

Output

root33 is a valid identifier.

33root is not a valid identifier.

root 33 is not a valid identifier.

4) count():

The count() method returns the number of occurrences of a substring in the given
string.

Example

message = 'python is popular programming language'

# number of occurrence of 'p'

print('Number of occurrence of p:', message.count('p'))

# Output: Number of occurrence of p: 4

Syntax of String count

The syntax of count() method is:

string.count(substring, start=..., end=...)


count() Parameters

count() method only requires a single parameter for execution. However, it also has
two optional parameters:

substring - string whose count is to be found.

start (Optional) - starting index within the string where search starts.

end (Optional) - ending index within the string where search ends.

Note: Index in Python starts from 0, not 1.

count() Return Value

count() method returns the number of occurrences of the substring in the given
string.

Example 1: Count number of occurrences of a given substring

# define string

string = "Python is awesome, isn't it?"

substring = "is"

count = string.count(substring)

# print count

print("The count is:", count)

Output:

The count is: 2


Example 2: Count number of occurrences of a given substring using start and
end

# define string

string = "Python is awesome, isn't it?"

substring = "i"

# count after first 'i' and before the last 'i'

count = string.count(substring, 8, 25)

# print count

print("The count is:", count)

Output:

The count is: 1

Here, the counting starts after the first i has been encountered, i.e. 7th index position.

And, it ends before the last i, i.e. 25th index position.

5) isprintable()

The isprintable() methods returns True if all characters in the string are printable or
the string is empty. If not, it returns False.

Characters that occupy printing space on the screen are known as printable
characters. For example:

letters and symbols

digits

punctuation

whitespace
The syntax of isprintable() is:

string.isprintable()

isprintable() Parameters

isprintable() doesn't take any parameters.

Return Value from isprintable()

The isprintable() method returns:

True if the string is empty or all characters in the string are printable

False if the string contains at least one non-printable character

Example 1: Working of isprintable()

s = 'Space is a printable'

print(s)

print(s.isprintable())

s = '\nNew Line is printable'

print(s)

print(s.isprintable())

s = ''

print('\nEmpty string printable?', s.isprintable())


Output:

Space is a printable

True

New Line is printable

False

Empty string printable? True

Example 2: How to use isprintable()?

# written using ASCII

# chr(27) is escape character

# char(97) is letter 'a'

s = chr(27) + chr(97)

if s.isprintable() == True:

print('Printable')

else:

print('Not Printable')
s = '2+2 = 4'

if s.isprintable() == True:

print('Printable')

else:

print('Not Printable')

Output:

Not Printable

Printable

6) casefold()

The casefold() method is an aggressive lower() method which converts strings to case
folded strings for caseless matching.

The casefold() method removes all case distinctions present in a string. It is used for
caseless matching, i.e. ignores cases when comparing.

For example, the German lowercase letter ß is equivalent to ss. However, since ß is
already lowercase, the lower() method does nothing to it. But, casefold() converts it
to ss.

The syntax of casefold() is:

string.casefold()

Parameters for casefold()

The casefold() method doesn't take any parameters.

Return value from casefold()

The casefold() method returns the case folded string.


Example 1: Lowercase using casefold()

string = "PYTHON IS AWESOME"

# print lowercase string

print("Lowercase string:", string.casefold())

Output:

Lowercase string: python is awesome

Example 2: Comparison using casefold()

firstString = "der Fluß"

secondString = "der Fluss"

# ß is equivalent to ss

if firstString.casefold() == secondString.casefold():

print('The strings are equal.')

else:

print('The strings are not equal.')

Output:

The strings are equal.


7) expandtabs()

The expandtabs() method returns a copy of string with all tab characters '\t' replaced
with whitespace characters until the next multiple of tabsize parameter.

The syntax of expandtabs() method is:

string.expandtabs(tabsize)

expandtabs() Parameters

The expandtabs() takes an integer tabsize argument. The default tabsize is 8.

Return Value from expandtabs()

The expandtabs() returns a string where all '\t' characters are replaced with
whitespace characters until the next multiple of tabsize parameter.

Example 1: expandtabs() With no Argument

str = 'xyz\t12345\tabc'

# no argument is passed

# default tabsize is 8

result = str.expandtabs()

print(result)

Output

xyz 12345 abc


How expandtabs() works in Python?

The expandtabs() method keeps track of the current cursor position.

The position of first '\t' character in the above program is 3. And, the tabsize is 8 (if
argument is not passed).

The expandtabs() character replaces the '\t' with whitespace until the next tab stop.
The position of '\t' is 3 and the first tab stop is 8. Hence, the number of spaces after
'xyz' is 5.

The next tab stops are the multiples of tabsize. The next tab stops are 16, 24, 32 and
so on.

Now, the position of second '\t' character is 13. And, the next tab stop is 16. Hence,
there are 3 spaces after '12345'.

Example 2: expandtabs() With Different Argument

str = "xyz\t12345\tabc"

print('Original String:', str)

# tabsize is set to 2

print('Tabsize 2:', str.expandtabs(2))

# tabsize is set to 3

print('Tabsize 3:', str.expandtabs(3))

# tabsize is set to 4

print('Tabsize 4:', str.expandtabs(4))


# tabsize is set to 5

print('Tabsize 5:', str.expandtabs(5))

# tabsize is set to 6

print('Tabsize 6:', str.expandtabs(6))

Output

Original String: xyz 12345 abc

Tabsize 2: xyz 12345 abc

Tabsize 3: xyz 12345 abc

Tabsize 4: xyz 12345 abc

Tabsize 5: xyz 12345 abc

Tabsize 6: xyz 12345 abc

Explanation

The default tabsize is 8. The tab stops are 8, 16 and so on. Hence, there is 5 spaces
after 'xyz' and 3 after '12345' when you print the original string.

When you set the tabsize to 2. The tab stops are 2, 4, 6, 8 and so on. For 'xyz', the tab
stop is 4, and for '12345', the tab stop is 10. Hence, there is 1 space after 'xyz' and 1
space after '12345'.

When you set the tabsize to 3. The tab stops are 3, 6, 9 and so on. For 'xyz', the tab
stop is 6, and for '12345', the tab stop is 12. Hence, there are 3 spaces after 'xyz' and
1 space after '12345'.

When you set the tabsize to 4. The tab stops are 4, 8, 12 and so on. For 'xyz', the tab
stop is 4 and for '12345', the tab stop is 12. Hence, there is 1 space after 'xyz' and 3
spaces after '12345'.
When you set the tabsize to 5. The tab stops are 5, 10, 15 and so on. For 'xyz', the tab
stop is 5 and for '12345', the tab stop is 15. Hence, there are 2 spaces after 'xyz' and
5 spaces after '12345'.

When you set the tabsize to 6. The tab stops are 6, 12, 18 and so on. For 'xyz', the tab
stop is 6 and for '12345', the tab stop is 12. Hence, there are 3 spaces after 'xyz' and
1 space after '12345'.

8) find()

In this tutorial, we will learn about the Python String find() method with the help of
examples.

The find() method returns the index of first occurrence of the substring (if found). If
not found, it returns -1.

Example

message = 'Python is a fun programming language'

# check the index of 'fun'

print(message.find('fun'))

# Output: 12

Syntax of String find()

The syntax of the find() method is:

str.find(sub[, start[, end]] )


find() Parameters

The find() method takes maximum of three parameters:

sub - It is the substring to be searched in the str string.

start and end (optional) - The range str[start:end] within which substring is searched.

find() Return Value

The find() method returns an integer value:

If the substring exists inside the string, it returns the index of the first occurence of
the substring.

If a substring doesn't exist inside the string, it returns -1.

Working of find() method


Example 1: find() With No start and end Argument

quote = 'Let it be, let it be, let it be'

# first occurance of 'let it'(case sensitive)

result = quote.find('let it')

print("Substring 'let it':", result)

# find returns -1 if substring not found

result = quote.find('small')

print("Substring 'small ':", result)

# How to use find()

if (quote.find('be,') != -1):

print("Contains substring 'be,'")

else:

print("Doesn't contain substring")

Output

Substring 'let it': 11

Substring 'small ': -1

Contains substring 'be,'


Example 2: find() With start and end Arguments

quote = 'Do small things with great love'

# Substring is searched in 'hings with great love'

print(quote.find('small things', 10))

# Substring is searched in ' small things with great love'

print(quote.find('small things', 2))

# Substring is searched in 'hings with great lov'

print(quote.find('o small ', 10, -1))

# Substring is searched in 'll things with'

print(quote.find('things ', 6, 20))

Output

-1

-1

9
9) rfind()

The rfind() method returns the highest index of the substring (if found). If not found,
it returns -1.

The syntax of rfind() is:

str.rfind(sub[, start[, end]] )

rfind() Parameters

rfind() method takes a maximum of three parameters:

sub - It's the substring to be searched in the str string.

start and end (optional) - substring is searched within str[start:end]

Return Value from rfind()

rfind() method returns an integer value.

If substring exists inside the string, it returns the highest index where substring is
found.

If substring doesn't exist inside the string, it returns -1.


Example 1: rfind() With No start and end Argument

quote = 'Let it be, let it be, let it be'

result = quote.rfind('let it')

print("Substring 'let it':", result)

result = quote.rfind('small')

print("Substring 'small ':", result)

result = quote.rfind('be,')

if (result != -1):

print("Highest index where 'be,' occurs:", result)

else:

print("Doesn't contain substring")

Output

Substring 'let it': 22

Substring 'small ': -1

Highest index where 'be,' occurs: 18


Example 2: rfind() With start and end Arguments

quote = 'Do small things with great love'

# Substring is searched in 'hings with great love'

print(quote.rfind('things', 10))

# Substring is searched in ' small things with great love'

print(quote.rfind('t', 2))

# Substring is searched in 'hings with great lov'

print(quote.rfind('o small ', 10, -1))

# Substring is searched in 'll things with'

print(quote.rfind('th', 6, 20))

Output

-1

25

-1

18
10) index()

In this tutorial, we will learn about the Python index() method with the help of
examples.

The index() method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.

Example

text = 'Python is fun'

# find the index of is

result = text.index('is')

print(result)

# Output: 7

index() Syntax

It's syntax is:

str.index(sub[, start[, end]] )

index() Parameters

The index() method takes three parameters:

sub - substring to be searched in the string str.

start and end(optional) - substring is searched within str[start:end]


index() Return Value

If substring exists inside the string, it returns the lowest index in the string where
substring is found.

If substring doesn't exist inside the string, it raises a ValueError exception.

The index() method is similar to the find() method for strings.

The only difference is that find() method returns -1 if the substring is not found,
whereas index() throws an exception.

Example 1: index() With Substring argument Only

sentence = 'Python programming is fun.'

result = sentence.index('is fun')

print("Substring 'is fun':", result)

result = sentence.index('Java')

print("Substring 'Java':", result)

Output

Substring 'is fun': 19

Traceback (most recent call last):

File "<string>", line 6, in

result = sentence.index('Java')
ValueError: substring not found

Note: Index in Python starts from 0 and not 1. So the occurrence is 19 and not 20.

Example 2: index() With start and end Arguments

sentence = 'Python programming is fun.'

# Substring is searched in 'gramming is fun.'

print(sentence.index('ing', 10))

# Substring is searched in 'gramming is '

print(sentence.index('g is', 10, -4))

# Substring is searched in 'programming'

print(sentence.index('fun', 7, 18))

Output

15

17

Traceback (most recent call last):

File "<string>", line 10, in

print(quote.index('fun', 7, 18))

ValueError: substring not found


11) rindex()

The rindex() method returns the highest index of the substring inside the string (if
found). If the substring is not found, it raises an exception.

The syntax of rindex() is:

str.rindex(sub[, start[, end]] )

rindex() Parameters

rindex() method takes three parameters:

sub - substring to be searched in the str string.

start and end(optional) - substring is searched within str[start:end]

Return Value from rindex()

If substring exists inside the string, it returns the highest index in the string where the
substring is found.

If substring doesn't exist inside the string, it raises a ValueError exception.

rindex() method is similar to rfind() method for strings.

The only difference is that rfind() returns -1 if the substring is not found,
whereas rindex() throws an exception.
Example 1: rindex() With No start and end Argument

quote = 'Let it be, let it be, let it be'

result = quote.rindex('let it')

print("Substring 'let it':", result)

result = quote.rindex('small')

print("Substring 'small ':", result)

Output

Substring 'let it': 22

Traceback (most recent call last):

File "...", line 6, in <module>

result = quote.rindex('small')

ValueError: substring not found

Note: Index in Python starts from 0 and not 1.

Example 2: rindex() With start and end Arguments

quote = 'Do small things with great love'

# Substring is searched in ' small things with great love'

print(quote.rindex('t', 2))
# Substring is searched in 'll things with'

print(quote.rindex('th', 6, 20))

# Substring is searched in 'hings with great lov'

print(quote.rindex('o small ', 10, -1))

Output

25

18

Traceback (most recent call last):

File "...", line 10, in <module>

print(quote.rindex('o small ', 10, -1))

ValueError: substring not found

12 partition()

The partition() method splits the string at the first occurrence of the argument string
and returns a tuple containing the part the before separator, argument string and the
part after the separator.

The syntax of partition() is:

string.partition(separator)

partition() Parameters()

The partition() method takes a string parameter separator that separates the string at
the first occurrence of it.
Return Value from partition()

The partition method returns a 3-tuple containing:

the part before the separator, separator parameter, and the part after the separator if
the separator parameter is found in the string

the string itself and two empty strings if the separator parameter is not found

Example: How partition() works?

string = "Python is fun"

# 'is' separator is found

print(string.partition('is '))

# 'not' separator is not found

print(string.partition('not '))

string = "Python is fun, isn't it"

# splits at first occurence of 'is'

print(string.partition('is'))

Output

('Python ', 'is ', 'fun')

('Python is fun', '', '')

('Python ', 'is', " fun, isn't it")


12) rpartition()

The rpartition() splits the string at the last occurrence of the argument string and
returns a tuple containing the part the before separator, argument string and the
part after the separator.

The syntax of rpartition() is:

string.rpartition(separator)

rpartition() Parameters()

rpartition() method takes a string parameter separator that separates the string at
the last occurrence of it.

Return Value from rpartition()

rpartition() method returns a 3-tuple containing:

the part before the separator, separator parameter, and the part after the separator if
the separator parameter is found in the string

two empty strings, followed by the string itself if the separator parameter is not
found

Example: How rpartition() works?

string = "Python is fun"

# 'is' separator is found

print(string.rpartition('is '))

# 'not' separator is not found

print(string.rpartition('not '))
string = "Python is fun, isn't it"

# splits at last occurence of 'is'

print(string.rpartition('is'))

Output

('Python ', 'is ', 'fun')

('', '', 'Python is fun')

('Python is fun, ', 'is', "n't it")


Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most
common and reliable type is the list.

A list can be defined as a collection of values or items of different types. The items in
the list are separated with the comma (,) and enclosed with the square brackets [].

A list can be define as below

L1 = ["John", 102, "USA"]


L2 = [1, 2, 3, 4, 5, 6]

IIf we try to print the type of L1, L2 using type() function then it will come out to be a
list.

print(type(L1))
print(type(L2))

Output:

<class 'list'>
<class 'list'>

Characteristics of Lists
The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o A list can store the number of various elements.
Let's check the first statement that lists are the ordered.

a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b

Output:

False

Both lists have consisted of the same elements, but the second list changed the index
position of the 5th element that violates the order of lists. When compare both lists it
returns the false.

Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.

a = [1, 2,"Peter", 4.50,"Ricky",5, 6]


b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b

Output:

True

Let's have a look at the list example in detail.

emp = ["John", 102, "USA"]


Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep
1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

In the above example, we have created the lists which consist of the employee and
department details and printed the corresponding details. Observe the above code
to understand the concept of the list better.

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The
elements of the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored
at the 0th index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.

list_varible(start:stop:step)

o The start denotes the starting index position of the list.


o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start:stop

Consider the following example:

list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -
1.
print(list[:])
print(list[2:5])
print(list[1:6:2])

Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

Unlike other languages, Python provides the flexibility to use the negative indexing
also. The negative indices are counted from the right. The last element (rightmost) of
the list has the index -1; its adjacent left element is present at the index -2 and so on
until the left-most elements are encountered.

Let's have a look at the following example where we will use negative indexing to
access the elements of the list.

list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])

Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As we discussed above, we can get an element by using negative indexing. In the
above code, the first print statement returned the rightmost element of the list. The
second print statement returned the sub-list, and so on.

Updating List values


Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.

Python also provides append() and insert() methods, which can be used to add
values to the list.

Consider the following example to update the values inside the list.

list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides
us the remove() method if we do not know which element is to be deleted from the
list.

Consider the following example to delete the list elements.


Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.

Let's see how the list responds to various operators.

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list elements to L1*2 = [1, 2, 3, 4, 1,
2, 3, 4]
be repeated multiple times.

Concatenation It concatenates the list mentioned on either side of l1+l2 = [1, 2, 3, 4,


5, 6, 7, 8]
the operator.

Membership It returns true if a particular item exists in a print(2 in l1) prints


True.
particular list otherwise false.

Iteration The for loop is used to iterate over the list for i in l1:
print(i)
elements.
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.

list = ["John", "David", "James", "Jonathan"]


for i in list:
# The i variable will iterate over the elements of the List and contains each element in each
iteration.
print(i)

Output:

John
David
James
Jonathan

Adding elements to the list


Python provides append() function which is used to add an element to the list.
However, the append() function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list from
the user and printing the list on the console.

#Declaring the empty list


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
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")

Output:

Enter the number of elements in the list:5


Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25 46 12 75 42
Removing elements from the list
Python provides the remove() function which is used to remove the element from
the list. Consider the following example to understand this concept.

Example -

list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")

Output:

printing original list:


0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4
Introduction:
In Python, you’ll be able to use a list function that creates a group that will be

manipulated for your analysis. This collection of data is named a list object.

While all methods are functions in Python, not all functions are methods. There’s a

key difference between functions and methods in Python. Functions take objects as

inputs while Methods in contrast act on objects.

Python offers the subsequent list functions:

• sort(): Sorts the list in ascending order.


• type(list): It returns the class type of an object.
• append(): Adds one element to a list.
• extend(): Adds multiple elements to a list.
• index(): Returns the first appearance of a particular value.
• max(list): It returns an item from the list with a max value.
• min(list): It returns an item from the list with a min value.
• len(list): It gives the overall length of the list.
• clear(): Removes all the elements from the list.
• insert(): Adds a component at the required position.
• count(): Returns the number of elements with the required value.
• pop(): Removes the element at the required position.
• remove(): Removes the primary item with the desired value.
• reverse(): Reverses the order of the list.
• copy(): Returns a duplicate of the list.
• cmp(list1, list2): It compares elements of both lists list1 and list2.
• list(seq): Converts a tuple into a list.
List Refresher

It is the primary, and certainly the foremost common container.

• A list is defined as an ordered, mutable, and heterogeneous collection of objects.


• To clarify: order implies that the gathering of objects follow a particular order
• Mutable means the list can be mutated or changed, and heterogeneous implies that
you’ll be able to mix and match any kind of object, or data type, within a list (int,
float, or string).
• Lists are contained within a collection of square brackets [ ].
Let’s see all the functions one by one with the help of an example,

1)sort() method:

The sort() method is a built-in Python method that, by default, sorts the list in

ascending order. However, you’ll modify the order from ascending to descending by

specifying the sorting criteria.

Example
Let’s say you would like to sort the elements of the product’s prices in ascending
order. You’d type prices followed by a . (period) followed by the method name, i.e.,
sort including the parentheses.

prices = [589.36, 237.81, 230.87, 463.98, 453.42]


prices.sort()
print(prices)
Output:

[ 230.87, 237.81, 453.42, 463.98, 589.36]

2)type() function
For the type() function, it returns the class type of an object.

Example
In this example, we will see the data type of the formed container.

fam = ["abs", 1.57, "egfrma", 1.768, "mom", 1.71, "dad"]


type(fam)
Output:

list
3)append() method
The append() method will add some elements you enter to the end of the elements
you specified.

Example
In this example, let’s increase the length of the string by adding the element “April”
to the list. Therefore, the append() function will increase the length of the list by 1.
months = ['January', 'February', 'March']
months.append('April')
print(months)
Output:

['January', 'February', 'March', 'April']

4)extend() method

The extend() method increases the length of the list by the number of elements that

are provided to the strategy, so if you’d prefer to add multiple elements to the

list, you will be able to use this method.

Example

In this example, we extend our initial list having three objects to a list having six

objects.

list = [1, 2, 3]
list.extend([4, 5, 6])
list

Output:

[1, 2, 3, 4, 5, 6]

5)index() method

The index() method returns the primary appearance of the required value.

Example

In the below example, let’s examine the index of February within the list of months.

months = ['January', 'February', 'March', 'April', 'May']


months.index('March')
Output:

6)max() function
The max() function will return the highest value from the inputted values.

Example
In this example, we’ll look to use the max() function to hunt out the foremost price
within the list named price.

prices = [589.36, 237.81, 230.87, 463.98, 453.42]


price_max = max(prices)
print(price_max)
Output:

589.36
7)min() function
The min() function will return the rock bottom value from the inputted values.

Example
In this example, you will find the month with the tiniest consumer indicator (CPI).

To identify the month with the tiniest consumer index, you initially apply the min()
function on prices to identify the min_price. Next, you’ll use the index method to
look out the index location of the min_price. Using this indexed location on months,
you’ll identify the month with the smallest consumer indicator.

months = ['January', 'February', 'March']


prices = [238.11, 237.81, 238.91]
# Identify min price
min_price = min(prices)
# Identify min price index
min_index = prices.index(min_price)
# Identify the month with min price
min_month = months[min_index]
print[min_month]
Output:

February
8)len() function

The len() function returns the number of elements in a specified list.

Example

In the below example, we are going to take a look at the length of the 2 lists using

this function.

list_1 = [50.29]
list_2 = [76.14, 89.64, 167.28]
print('list_1 length is ', len(list_1))
print('list_2 length is ', len(list_2))

Output:

list_1 length is 1
list_2 length is 3
9)clear() function

The clear() method removes all the elements from a specified list and converts them

to an empty list.

Example

In this example, we’ll remove all the elements from the month’s list and make the list

empty.

months = ['January', 'February', 'March', 'April', 'May']


months.clear()

Output:

[]
10)insert() function

The insert() method inserts the required value at the desired position.

Example

In this example, we’ll Insert the fruit “pineapple” at the third position of the fruit list.

fruits = ['apple', 'banana', 'cherry']


fruits.insert(2, "pineapple")

Output:

['apple', 'banana', 'pineapple', 'cherry']


11)count() function

The count() method returns the number of elements with the desired value.

Example

In this example, we are going to return the number of times the fruit “cherry”

appears within the list of fruits.

fruits = ['cherry', 'apple', 'cherry', 'banana', 'cherry']


x = fruits.count("cherry")
Output:

3
12)pop() function
The pop() method removes the element at the required position.

Example
In this example, we are going to remove the element that’s on the third location of
the fruit list.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.pop(2)
Output:

['apple', 'banana', 'orange', 'pineapple']


13)remove() function

The remove() method removes the first occurrence of the element with the

specified value.

Example

In this example, we will Remove the “banana” element from the list of fruits.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.remove("banana")

Output:

['apple', 'cherry', 'orange', 'pineapple']


14)reverse() function

The reverse() method reverses the order of the elements.

Example

In this example, we will be reverse the order of the fruit list, so that the first element

in the initial list becomes last and vice-versa in the new list.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.reverse()

Output:

['pineapple', 'orange', 'cherry', 'banana', 'apple']


15)copy() function
The copy() method returns a copy of the specified list and makes the new list.

Example
In this example, we want to create a list having the same elements as the list of fruits.

fruits = ['apple', 'banana', 'cherry', 'orange']


x = fruits.copy()
Output:

['apple', 'banana', 'cherry', 'orange']


16)cmp() function

For the cmp() function, it takes two values and compares them against one another.

It will then return a negative, zero, or positive value based on what was inputted.

Example

In the example below, we have two stock prices, and we will compare the integer

values to see which one is larger:

stock_price_1 = [50.23]

stock_price_2 = [75.14]

print(cmp(stock_price_1, stock_price_2))

print(cmp(stock_price_1, stock_price_1))

print(cmp(stock_price_2, stock_price_1))

When you run the above code, it produces the following result:

-1

The results show that the stock_price_2 list is larger than the stock_price_1 list. You

can use the cmp() function on any type of list, such as strings. Note that by default, if

one list is longer than the other, it will be considered to be larger.


17)list() function:

The list() function takes an iterable construct and turns it into a list.

Syntax

list([iterable])

Example

In the below example, you will be working with stock price data. Let's print out an
empty list, convert a tuple into a list, and finally, print a list as a list.

# empty list

print(list())

# tuple of stock prices

stocks = ('238.11', '237.81', '238.91')

print(list(stocks))

# list of stock prices

stocks_1 = ['238.11', '237.81', '238.91']

print(list(stocks_1))

When you run the above code, it produces the following result:

[]

['238.11', '237.81', '238.91']


['238.11', '237.81', '238.91']

Let’s see all the methods one by one with the help of an example.
1)append() method
The append() method will add some elements you enter to the end of the elements
you specified.
Example
In this example, let’s increase the length of the string by adding the element “April”
to the list. Therefore, the append() function will increase the length of the list by 1.

months = ['January', 'February', 'March']


months.append('April')
print(months)
Output:

['January', 'February', 'March', 'April']

2)extend() method

The extend() method increases the length of the list by the number of elements that

are provided to the strategy, so if you’d prefer to add multiple elements to the

list, you will be able to use this method.

Example

In this example, we extend our initial list having three objects to a list having six

objects.

list = [1, 2, 3]
list.extend([4, 5, 6])
list

Output:

[1, 2, 3, 4, 5, 6]

3)index() method

The index() method returns the primary appearance of the required value.

Example

In the below example, let’s examine the index of February within the list of months.
months = ['January', 'February', 'March', 'April', 'May']
months.index('March')

Output:

4)insert() function

The insert() method inserts the required value at the desired position.

Example

In this example, we’ll Insert the fruit “pineapple” at the third position of the fruit list.

fruits = ['apple', 'banana', 'cherry']


fruits.insert(2, "pineapple")

Output:

['apple', 'banana', 'pineapple', 'cherry']

5)count() function

The count() method returns the number of elements with the desired value.

Example

In this example, we are going to return the number of times the fruit “cherry”

appears within the list of fruits.

fruits = ['cherry', 'apple', 'cherry', 'banana', 'cherry']


x = fruits.count("cherry")
Output:

3
6)pop() function
The pop() method removes the element at the required position.
Example

In this example, we are going to remove the element that’s on the third location of

the fruit list.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.pop(2)

Output:

['apple', 'banana', 'orange', 'pineapple']

7)remove() function

The remove() method removes the first occurrence of the element with the

specified value.

Example

In this example, we will Remove the “banana” element from the list of fruits.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.remove("banana")

Output:

['apple', 'cherry', 'orange', 'pineapple']

8)copy() function
The copy() method returns a copy of the specified list and makes the new list.

Example
In this example, we want to create a list having the same elements as the list of fruits.

fruits = ['apple', 'banana', 'cherry', 'orange']


x = fruits.copy()
Output:

['apple', 'banana', 'cherry', 'orange']


9)reverse() function

The reverse() method reverses the order of the elements.

Example

In this example, we will be reverse the order of the fruit list, so that the first element

in the initial list becomes last and vice-versa in the new list.

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']


fruits.reverse()

Output:

['pineapple', 'orange', 'cherry', 'banana', 'apple']

10)clear() function

The clear() method removes all the elements from a specified list and converts them

to an empty list.

Example

In this example, we’ll remove all the elements from the month’s list and make the list

empty.

months = ['January', 'February', 'March', 'April', 'May']


months.clear()

Output:

[]
11)sort() method:

The sort() method is a built-in Python method that, by default, sorts the list in

ascending order. However, you’ll modify the order from ascending to descending by

specifying the sorting criteria.

Example
Let’s say you would like to sort the elements of the product’s prices in ascending
order. You’d type prices followed by a . (period) followed by the method name, i.e.,
sort including the parentheses.

prices = [589.36, 237.81, 230.87, 463.98, 453.42]


prices.sort()
print(prices)
Output:

[ 230.87, 237.81, 453.42, 463.98, 589.36]


Python List Built-in functions
Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

1 cmp(list1, It compares the elements of This method is not used in the Python 3 and the
list2) both the lists. above versions.

2 len(list) It is used to calculate the length L1 = [1,2,3,4,5,6,7,8]


print(len(L1))
of the list. 8

3 max(list) It returns the maximum L1 = [12,34,26,48,72]


print(max(L1))
element of the list. 72

4 min(list) It returns the minimum element L1 = [12,34,26,48,72]


print(min(L1))
of the list. 12

5 list(seq) It converts any sequence to the str = "Johnson"


s = list(str)
list. print(type(s))
<class list>

Let's have a look at the few list examples.

Example: 1- Write the program to remove the duplicate element of the list.

list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)

Output:

[1, 2, 3, 55, 98, 65, 13, 29]


Example:2- Write a program to find the sum of the element in the list.

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)

Output:

The sum is: 67

Example: 3- Write the program to find the lists consist of at least one common
element.

list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)

Output:

The common element is: 2

You might also like