0% found this document useful (0 votes)
52 views

Unit-2 Sem-V Python-I

The document discusses various string manipulation functions in Python including: 1. Upper(), lower(), title() etc. to change case of strings. 2. isdigit(), isalpha() etc. to check string properties. 3. strip(), lstrip(), rstrip() to remove whitespace. 4. replace() to replace substrings. 5. split() to split a string into a list. 6. join() to join a list of strings into one string.
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)
52 views

Unit-2 Sem-V Python-I

The document discusses various string manipulation functions in Python including: 1. Upper(), lower(), title() etc. to change case of strings. 2. isdigit(), isalpha() etc. to check string properties. 3. strip(), lstrip(), rstrip() to remove whitespace. 4. replace() to replace substrings. 5. split() to split a string into a list. 6. join() to join a list of strings into one string.
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
You are on page 1/ 87

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 in Python is a built-in data type, used to store multiple items in a single variable.
That is, when we need to store collection of data in a single variable, then we use
list.

Note - List items are ordered, changeable, and allows duplicates.

List items are ordered, means that all the items (elements or values) of the list are
numbered. For example, if there is a list named mylist, then mylist[0] refers to the
first element, whereas the mylist[1] refers to the second element, and so on.

List items are changeable, means that we can change the items of the list further,
after initialization.

List items allows duplicate values, means that in a particular list, there may be two or
more items with same values.

Create an Empty List in Python - Syntax

An empty list can be created in following two ways:

1. Using square brackets. That is, [ ]


2. Using list() constructor

Create an Empty List using Square Bracket

Here is the syntax to create an empty list in Python, using the square bracket:

listName = []

Create an Empty List using list() Constructor

To create an empty list using list() constructor, then use following syntax:

listName = list()

Create a List in Python - Syntax

Here is the syntax to create a list with values in Python:

listName = [value1, value2, value3, ..., valueN]

where value1, value2, value3 etc. can be of any data type such as integer, floating-
point, boolean, string, character etc. Also, can be a list too.
Another way that we can create a list, is by using the list() constructor. Here is the
syntax:

listName = list((value1, value2, value3, ..., valueN))

Note - Keep the double bracket in mind.

Create and Print a List in Python - Example

This is the first example of this article on list. This example program creates a list
and then prints the list as it is, on the output screen.

mylist = [1, 2, 3, 4, 5]
print(mylist)

mylist = [1, 'c', True, "codescracker", 12.4, 43]


print(mylist)

The same program can also be created in this way:

mylist = list((1, 2, 3, 4, 5))


print(mylist)

mylist = list((1, 'c', True, "codescracker", 12.4, 43))


print(mylist)

The snapshot given below shows the output produced by above Python code on list:

As already told, that the list is a kind of built-in data types in Python. The list can be
used to store multiple values in a single variable, as shown in the program given
above. That is, the values 1, 2, 3, 4, 5 is initialized to a single variable
say mylist using the first statement. Similar things done to define a list using third
statement.

Note - List items are indexed in a way that the first item stored at 0th index, whereas
the second item stored at 1st index, and so on.
Can List Contain Elements of Different Types ?

Yes, of course. The list elements can be of same or of different types. Here is an
example:

x = [12, 'c', 32.54, "codes", True]


print(x)

The output would be:

[12, 'c', 32.54, 'codes', True]

Python Access and Print List Element using Index

The element of a list can be accessed using its index in either from forward indexing
or through backward (negative) indexing. The snapshot given below shows both
forward and backward indexing:

That is, to access the very first element of a list named mylist, we need to
use mylist[0], whereas to access the last element of a list, we need to use mylist[-
1]. Here is an example showing how to access and print the list elements using
forward indexing.

mylist = [1, 2, 3, 4, 5]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])
print(mylist[4])

The output produced by this Python program is:

1
2
3
4
5
Here is another program shows how we can access elements of a list, using
backward indexing:

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

Here is the output produced by this program:

5
4
3
2
1

I know the above program looks weird, because what if there are more elements in
the list, then writing the print() statement along with index number, for all the
elements, is not possible, and also takes too much time. Therefore, we need to use
loop to print list elements. The example program based on it is given below.

Python Print List Elements using Loop

This program does the same job as of previous program. The only difference is its
approach. That is, this program uses for loop to do the job:

mylist = [1, 2, 3, 4, 5]
for element in mylist:
print(element)

You'll get the same output as of previous program's output.

Print all Elements of List using Loop, in Single Line

Most of the time, we need to print all list elements in a single line. Therefore this
program shows how to code in Python, so that the list elements gets printed in single
line, instead of multiple:

mylist = [1, 2, 3, 4, 5]
for element in mylist:
print(element, end=" ")

Here is its output:

1 2 3 4 5
Note - The end parameter is used to skip insertion of an automatic newline,
using print().

Python Create and Print a List with User Input

Now let's create another example program on list, that allows user to define the size
and elements of a list. The defined list elements will get printed back on the output
screen:

print("How many element to store in the list: ", end="")


n = int(input())
print("Enter", n, "elements for the list: ", end="")
mylist = []
for i in range(n):
val = input()
mylist.append(val)

print("\nThe list is:")


for i in range(n):
print(mylist[i], end=" ")

Sample run with user input 5 as size of list, and 10, 20, 30, 40, 50 as its five
elements, is shown in the snapshot given below:

Python List Length - Find Length of a List

The len() function plays an important role in most of the program in Python when
working with list, specially when working with a list whose elements are defined by
user at run-time of the program. Because in that case, the function len() finds the
length of the list, and that length plays of course a crucial role most of the time. Let's
take a look at one of the simplest example, uses len() function:

mylist = [1, 2, 3, 4, 5]
print("\nLength of List =", len(mylist))

Following is its sample output:

Length of List = 5

Another way to find and print the length of a list, without using len() method, is:

mylist = [1, 2, 3, 4, 5]
count = 0
for element in mylist:
count = count+1
print("\nList contains", count, "items.")

The output produced by above program is:

List contains 5 items.

Python List Slicing - Forward

Here is the syntax to slice a list in Python:

listVariable[startIndex, endIndex, step]

where startIndex is the starting index number from where the slice to start. The
element at this index is included. The endIndex is the last index number at which the
slice to stop. The element at this index is excluded. And the step is used when we
need to slice items of a list, along with skipping every nth element in between, while
slicing.

Note - By default, the startIndex value is 0, the endIndex value is equal to the
length of the list, and step value is equal to 1.

Before consider an example of list slicing in Python. Let's have a look at the following
list:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now:

• mylist[0:] gives or returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


• mylist[:] gives [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• mylist[:10] gives [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• mylist[2:4] gives [3, 4]
• mylist[2:8:3] gives [3, 6]
• mylist[2:9:3] gives [3, 6, 9]
• mylist[::3] gives [1, 4, 7, 10]

Now here is an example of list slicing in Python. This program sliced a list
named mylist in multiple ways, so that all the concept of list slicing (forward) will
easily get cleared using a single program:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("The original list is:")


print("mylist =", mylist)

print("\nList slicing example:")


print("mylist[0:] =", mylist[0:])
print("mylist[:] =", mylist[:])
print("mylist[:10] =", mylist[:10])
print("mylist[2:4] =", mylist[2:4])
print("mylist[2:8:3] =", mylist[2:8:3])
print("mylist[2:9:3] =", mylist[2:9:3])
print("mylist[::3] =", mylist[::3])

The snapshot given below shows the sample output produced by above Python
code, on list slicing:
Python List Slicing - Backward

The element at index -1 will get considered as the last element of the list, whereas
the element at index -lengthOfList will get considered as the first element of the list.
Here is an example of list slicing using negative indexing:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("The original list is:")


print("mylist =", mylist)

print("\nList slicing example (using backward indexing):")


print("mylist[-10:] =", mylist[-10:])
print("mylist[-8:] =", mylist[-8:])
print("mylist[:] =", mylist[:])
print("mylist[:-1] =", mylist[:-1]) # second index's value is
excluded
print("mylist[:-4] =", mylist[:-4])
print("mylist[-4:-2] =", mylist[-4:-2])
print("mylist[-8:-2:3] =", mylist[-8:-2:3])
print("mylist[-9:-2:3] =", mylist[-9:-2:3])
print("mylist[-10:-1:3] =", mylist[-10:-1:3])
print("mylist[::3] =", mylist[::3])

Sample run of above Python code is shown in the snapshot given below:
Python List Append - Add New Element to a List

Because list items are changeable, therefore we can add required elements to a list
anytime. Elements can be added either at the end of a list or at a given index. Let's
start with adding an element of a list at the end of a list in Python.

Add New Element at the End of a List

The append() method is used when we need to add an element at the end of a list.
Here is an example:

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

print("The original list is:")


print("mylist =", mylist)

print("\nEnter an Element to add: ", end="")


element = int(input())
mylist.append(element)

print("\nNow the list is:")


print("mylist =", mylist)
The snapshot given below shows the sample run of above Python program, with
user input 10 as element to add:

Add New Element in a List at Given Index

The insert() method is used when we need to insert an element at specified index in
a list. Here is an example:

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

print("The original list is:")


print("mylist =", mylist)

print("\nEnter an Element to add: ", end="")


element = int(input())
print("At what index ? ", end="")
index = int(input())

if index <= len(mylist):


mylist.insert(index, element)
print("\nNow the list is:")
print("mylist =", mylist)
else:
print("\nInvalid Index Number!")

Sample run with user input 500 as element and 3 as index number to add a new
element to the list, is shown in the snapshot given below:
Here is another example demonstrating how an element can be inserted at a
specified index in a list.

mylist = ['c', 'o', 'd', 's', 'c']

print("The original list is:")


print("mylist =", mylist)

mylist.insert(3, 'e')
print("\n1. Now the list is:")
print("mylist =", mylist)

mylist.insert(6, 'r')
print("\n2. Now the list is:")
print("mylist =", mylist)

mylist[7:10] = ['a', 'c', 'k', 'e']


print("\n3. Now the list is:")
print("mylist =", mylist)

mylist.insert(11, 'r')
print("\n4. Now the list is:")
print("mylist =", mylist)

To add element at particular index, without removing the previous value available at
that index, use insert(). While using insert() to insert an element at specified index,
all the elements after that index moved to one index forward.
Python Replace Single or Multiple Elements in a List

Use direct initialization of single or multiple values to a single or multiple indexes to


add new element(s) to a list. But the element(s) get replaced available at index(es)
that was used for the initialization. Here is its sample program, demonstrating the
concept:

mylist = ['c', 'o', 'd', 's', 'c']

print("The original list is:")


print("mylist =", mylist)

mylist[3] = 'x'
print("\n1. Now the list is:")
print("mylist =", mylist)

mylist[3:5] = ['e', 's']


print("\n2. Now the list is:")
print("mylist =", mylist)

mylist[5:12] = ['c', 'r', 'a', 'c', 'k', 'e', 'r']


print("\n3. Now the list is:")
print("mylist =", mylist)

mylist[3] = 'x'
print("\n4. Now the list is:")
print("mylist =", mylist)

mylist[2:8] = 'z'
print("\n5. Now the list is:")
print("mylist =", mylist)

mylist[1:6] = ['a', 'b']


print("\n6. Now the list is:")
print("mylist =", mylist)

mylist[:] = 'x'
print("\n7. Now the list is:")
print("mylist =", mylist)

Let's concentrate on the output of above program, to get the concept.

The original list is:


mylist = ['c', 'o', 'd', 's', 'c']

1. Now the list is:


mylist = ['c', 'o', 'd', 'x', 'c']

2. Now the list is:


mylist = ['c', 'o', 'd', 'e', 's']

3. Now the list is:


mylist = ['c', 'o', 'd', 'e', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r']

4. Now the list is:


mylist = ['c', 'o', 'd', 'x', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r']
5. Now the list is:
mylist = ['c', 'o', 'z', 'c', 'k', 'e', 'r']

6. Now the list is:


mylist = ['c', 'a', 'b', 'r']

7. Now the list is:


mylist = ['x']

Add Multiple Elements at the End of a List at Once

The extend() function is used when we need to add multiple elements at the end of
a list, without converting the list into a nested list. Here is an example:

mylist = [1, 2, 3]
mylist.extend([4, 5])
print(mylist)
[1, 2, 3, 4, 5]

Add Two List

The + operator helps in addition of the two lists. Below is an example of list addition
in Python:

listOne = ['p', 'y', 't']


listTwo = ['h', 'o', 'n']

listThree = listOne + listTwo


print(listThree)

listOne = listOne + listTwo


print(listOne)

Here is its sample output:

['p', 'y', 't', 'h', 'o', 'n']


['p', 'y', 't', 'h', 'o', 'n']

Python List Remove

Like adding an element in a list, sometime we also need to remove an element from
a list. The list element can be removed in either of the two ways:

1. using the remove() method


2. using the pop() method
Remove Element from a List using remove()

The remove() method is used when we need to remove an element from a list, using
element by value.

mylist = [11, 22, 33, 44, 55]


print("The list is:")
print(mylist)

mylist.remove(44)
print("\nNow the list is:")
print(mylist)

The output is:

The list is:


[11, 22, 33, 44, 55]

Now the list is:


[11, 22, 33, 55]

Remove Element from List using pop()

The pop() method is used when we need to pop an element from a list, using
element by index.

mylist = [11, 22, 33, 44, 55]


print("The list is:")
print(mylist)

mylist.pop(3)
print("\nNow the list is:")
print(mylist)

You'll get the same output as of previous program's output.

Delete Multiple Items from a List at Once using del Keyword

The del keyword is used when we need to delete multiple elements from a list. The
keyword del can also be used to delete the whole list. Here is an example:

x = ['p', 'y', 't', 'h', 'o', 'n']


print(x)
del x[1]
print(x)
del x[1:4]
print(x)
del x
The output produced by this program is given below:

['p', 'y', 't', 'h', 'o', 'n']


['p', 't', 'h', 'o', 'n']
['p', 'n']

After using the del x statement, the whole list x gets deleted. And if you try to print x,
then the program produces an error like this:

This output produced, after adding print(x) as the last statement of the above
program.

Python List Functions

These are the functions that can be used while working with list in Python. All these
functions are important in list point of view. I've described about all these functions,
in very brief. To learn in detail, you can refer to its separate tutorial.

• list() - Converts a sequence to a list


• len() - Returns the length of a list
• append() - Used to add new element at the end of a list.
• extend() - Used to add multiple elements or an iterable at the end of a list
• insert() - Inserts an element at specified index
• remove() - Removes the first occurrence of an element with specified value, from a
list
• pop() - Used to remove an item from the list
• max() - Returns the maximum item in an iterable, or the maximum between/among
two/multiple arguments
• min() - Returns the minimum item in an iterable, or the minimum between/among
two/multiple arguments
• clear() - Used to empty the list
• index() - Returns the index number of the first occurrence of a specified value in a list
• count() - Returns the number of occurrence of a particular element in a list
• sort() - Used to sort a list
• sorted() - Returns the sorted list
• reverse() - Used to reverse the elements of a list
• reversed() - Returns the reversed list
• copy() - Used to copy a list

Python Nested List - List of Lists

A list can be nested inside another list. That is, when we add a list itself instead of an
element, when initializing the elements to a list, then the list becomes a nested list.
Here is an example:

mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]


print("Direct:")
print(mylist)

print("\nUsing loop:")
for x in mylist:
print(x)

Here is its sample output:

Direct:
[1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]

Using loop:
1
[2, 3, 4]
5
6
[7, 8, 9, 10]

Here is another example of nested list (list of list(s)):

mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]


print(mylist[0])
print(mylist[1][0])
print(mylist[1][1])
print(mylist[1][2])
print(mylist[2])
print(mylist[3])
print(mylist[4][0])
print(mylist[4][1])
print(mylist[4][2])
print(mylist[4][3])
1
2
3
4
5
6
7
8
9
10

This is the last example of nested list or list of lists in Python. This program uses a
list named books_list in which all the elements are itself a list of 2 elements each.
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:

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

You might also like