0% found this document useful (0 votes)
2 views31 pages

Python Unit - 3

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)
2 views31 pages

Python Unit - 3

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

Leela Soft Python Madhu

Python Strings Revisited


Concatenating, Appending, and Multiplying Strings
String Concatenation in Python
String Concatenation is the technique of combining two strings. String Concatenation can be
done using many ways.

We can perform string concatenation using following ways:


 Using + operator
 Using join() method
 Using % operator
 Using format() function

Using + Operator
It’s very easy to use + operator for string concatenation. This operator can be used to add multiple
strings together. However, the arguments must be a string.

Note: Strings are immutable, therefore, whenever it is concatenated, it is assigned to a new


variable.

Example:
# Python program to demonstrate string concatenation
# Defining strings
var1 = "Hello "
var2 = "World"

# + Operator is used to combine strings


var3 = var1 + var2
print(var3)

Using join() Method


The join() method is a string method and returns a string in which the elements of sequence
have been joined by str separator.

Example:
# Python program to demonstrate string concatenation
var1 = "Hello"
var2 = "World"

# join() method is used to combine the strings


print("".join([var1, var2]))

# join() method is used here to combine


# the string with a separator Space(" ")
var3 = " ".join([var1, var2])

print(var3)

www.leelasoft.com Page 1 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

Using % Operator
We can use % operator for string formatting, it can also be used for string concatenation. It’s
useful when we want to concatenate strings and perform simple formatting.

Example:
# Python program to demonstrate string concatenation

var1 = "Hello"
var2 = "World"

# % Operator is used here to combine the string


print("% s % s" % (var1, var2))

Using format() function


str.format() is one of the string formatting methods in Python, which allows multiple
substitutions and value formatting. This method lets us concatenate elements within a string
through positional formatting.

Example:
# Python program to demonstrate string concatenation

var1 = "Hello"
var2 = "World"

# format function is used here to # combine the string


print("{} {}".format(var1, var2))

# store the result in another variable


var3 = "{} {}".format(var1, var2)

print(var3)

Appending Strings in Python:


Using += operator:
This operator can be used to perform this particular task of concatenating the string. This is quite
simpler than the traditional methods that are employed in other languages, like using a dedicated
function to perform this particular task.

Example:
# Python code to demonstrate Adding one string to another Using +=
operator

# initializing string
test_string = "GFG"

# initializing add_string

www.leelasoft.com Page 2 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
add_string = " is best"

# printing original string


print("The original string : " + str(test_string))

# printing original add string


print("The add string : " + str(add_string))

# Using += operator adding one string to another


test_string += add_string

# print result
print("The concatenated string is : " + test_string)

Multiplying Strings (Repetition):


Sequences datatypes (both mutable and immutable) support a repetition operator * The
repetition operator * will make multiple copies of that particular object and combines them
together. When * is used with an integer it performs multiplication but with list, tuple or strings
it performs a repetition.

Syntax: a*b
Here: a is integer and b is string or vice versa

Example 1: Repetition operator on Strings


s1="python"
print (s1*3)

#Output: pythonpythonpython

String Formatting Operator:


String objects have one unique built-in operation: the % operator (modulo). This is also known as
the string formatting or interpolation operator. Given format % values (where format is a
string), % conversion specifications in format are replaced with zero or more elements of values.
The effect is similar to using the sprintf() in the C language.

If format requires a single argument, values may be a single non-tuple object. Otherwise, values
must be a tuple with exactly the number of items specified by the format string, or a single
mapping object.

The syntax for the string formatting operation is:


"<FORMAT>" % (<VALUES>)

The conversion types are:


Conversion Meaning
'd' Signed integer decimal.
'i' Signed integer decimal.

www.leelasoft.com Page 3 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
'o' Signed octal value.
'u' Obsolete type – it is identical to 'd'.
'x' Signed hexadecimal (lowercase).
'X' Signed hexadecimal (uppercase).
'e' Floating point exponential format (lowercase).
'E' Floating point exponential format (uppercase).
'f' Floating point decimal format.
'F' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or
not less than precision, decimal format otherwise.
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or
not less than precision, decimal format otherwise.
'c' Single character (accepts integer or single character string).
'r' String (converts any Python object using repr()).'s'
's' String (converts any Python object using str()).'a'
'a' String (converts any Python object using ascii()).'%'
'%' No argument is converted, results in a '%' character in the result.

Example: 1
# This Example shows simple substitution.
print('%d' % 100)
'100'
print('%d' % 0b1111)
'15'
print("%s" % 'foo')
'foo'
print("%s %s" % ('foo', 'bar'))
'foo bar'
dct = {'foo': 10, 'bar': 20}
print("%(foo)s" % dct)
'10'

Example: 2
# This Example shows usage of # flag (alternate form).
print("%x" % 17)
'11'
print("%#x" % 17)
'0x11'
print("%#X" % 17)
'0X11'

Example 3: # This Example shows usage of zero padding and width flags.
>>> "%d" % 1
'1'
>>> "%03d" % 1
'001'

Example 4 : # This Example shows usage of left adjust flag.


>>> "%d" % 1

www.leelasoft.com Page 4 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
'1'
>>> "%-5d" % 1
'1 '
>>> "%0-5d" % 1
'1 '

Example 5: # This Example shows usage of space flag


>>> '%d' % 1 .
'1'
>>> '%d' % -1
'-1'
>>> '% d' % 1
' 1'
>>> '% d' % -1
'-1'

Example 6: # This Example shows usage of sign flag.


>>> '%d' % 1
'1'
>>> '%+d' % 1
'+1'
>>> '%+d' % -1
'-1'
>>> '% +d' % -1
'-1'
>>> '% +d' % 1
'+1'

Example 7: # This Example shows usage of precision modifier.


>>> '%f' % 3.14
'3.140000'
>>> '%.1f' % 3.14
'3.1'
>>> '%.2f' % 3.14
'3.14'
>>> '%.3f' % 3.14
'3.140'

Example 8: # This Example shows how to covert to signed integer


decimals.
>>> '%i' % 0b1111
'15'
>>> '%d' % 0b1111
'15'
>>> '%d' % 10
'10'
>>> '%d' % 3.14
'3'
>>> '%i' % 3.14

www.leelasoft.com Page 5 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
'3'
>>> '%i' % -10
'-10'

Example 9: # Hex and octal conversions.


>>> '%x' % 27
'1b'
>>> '%X' % 27
'1B'
>>> '%o' % 27
'33'

Example 10: #Float conversions.


>>> '%f' % 10 #
'10.000000'
>>> '%F' % 10
'10.000000'
>>> '%g' % 1234567890
'1.23457e+09'
>>> '%G' % 1234567890
'1.23457E+09'
>>> '%e' % 1234567890
'1.234568e+09'
>>> '%E' % 1234567890
'1.234568E+09'

Example 11:# Character and string conversions.


>>> 'ABC %c' % 10
'ABC \n'
>>> 'ABC %c' % 67
'ABC C'
>>> 'ABC %c' % 68
'ABC D'
>>> 'ABC %c' % 'D'
'ABC D'
>>> 'ABC %s' % 68
'ABC 68'
>>> 'ABC %r' % 68
'ABC 68'

Python String Methods


Python String capitalize()
Converts first character to Capital Letter

string = "python is AWesome."


capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)

www.leelasoft.com Page 6 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
Python String casefold()
converts to case folded strings

string = "PYTHON IS AWESOME"


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

Python String center()


Pads string with specified character

string = "Python is awesome"


new_string = string.center(24, '*')
print("Centered String: ", new_string)

Python String count()


returns occurrences of substring in string

# define string
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)

Python String lower()


returns lowercased string

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())

# string with numbers # all alphabets whould be lowercase


string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

Python String upper()


returns uppercased string

# example string
string = "this should be uppercase!"
print(string.upper())

# string with numbers # all alphabets whould be lowercase


string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())

Python String split()

www.leelasoft.com Page 7 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
Splits String from Left

text= 'Love thy neighbor'

# splits at space
print(text.split())

grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.split(', '))

# Splitting at ':'
print(grocery.split(':'))

Built in String Functions:


len() Python String length can be determined by using built-in len() function.

#Given string whose length is to be found


str1="Python is great!"
print("The given String is:",str1)

#calling our len() method to calculate #the length of str1


print("Length =",len(str1))

ord() Python ord() function takes string argument of a single Unicode character and return its
integer Unicode code point value.

x = ord('A')
print(x)

print(ord('ć'))
print(ord('ç'))
print(ord('$'))

float() As the name says, python float() function returns a floating point number from the input
argument.

# init a string with the value of a number


str_to_float = '12.60'
# check the type of the variable
print('The type of str_to_float is:', type(str_to_float))
# use the float() function
str_to_float = float(str_to_float)
# now check the type of the variable
print('The type of str_to_float is:', type(str_to_float))

www.leelasoft.com Page 8 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
int() Python int() function returns an integer object from the specified input. The returned int
object will always be in base 10.

x = int("5")
print(x)

x = int("-0xf", base=16)
print(x)

x = int("0b111", base=2)
print(x)

String Comparison in Python


Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the
zeroth index till the end of the string. It then returns a boolean value according to the operator
used.

Example:
print("Leela" == "Leela")
print("Leela" < "leela")
print("Leela" > "leela")
print("Leela" != "Leela")

Method 2: Using is and is not


The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same
is the case for != and is not.

Example:
str1 = "AGSG"
str2 = "AGSG"
str3 = str1

print("ID of str1 =", hex(id(str1)))


print("ID of str2 =", hex(id(str2)))
print("ID of str3 =", hex(id(str3)))
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)

str1 += "s"
str4 = "AGSGs"

print("\nID of changed str1 =", hex(id(str1)))


print("ID of str4 =", hex(id(str4)))
print(str1 is str4)

www.leelasoft.com Page 9 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

Regular Expression
A (Very Brief) History of Regular Expressions
In 1951, mathematician Stephen Cole Kleene described the concept of a regular language, a
language that is recognizable by a finite automaton and formally expressible using regular
expressions. In the mid-1960s, computer science pioneer Ken Thompson, one of the original
designers of Unix, implemented pattern matching in the QED text editor using Kleene’s notation.

Since then, regexes have appeared in many programming languages, editors, and other tools as
a means of determining whether a string matches a specified pattern. Python, Java, and Perl all
support regex functionality, as do most Unix tools and many text editors.

Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly
specialized programming language embedded inside Python and made available through the re
module.

Using this little language, we specify the rules for the set of possible strings that we want to
match; this set might contain English sentences, or e-mail addresses, or TeX commands, or
anything we like. We can then ask questions such as “Does this string match the pattern?”, or
“Is there a match for the pattern anywhere in this string?”. We can also use REs to modify a
string or to split it apart in various ways.

Regular expression patterns are compiled into a series of bytecodes which are then executed by
a matching engine written in C. For advanced use, it may be necessary to pay careful attention
to how the engine will execute a given RE, and write the RE in a certain way in order to produce
bytecode that runs faster.

The re Module Contents:


The module defines several functions, constants, and an exception. Some of the functions are
simplified versions of the full featured methods for compiled regular expressions. Most non-
trivial applications always use the compiled form.

RegEx Functions
This module exports the following functions:
Function Description
match Match a regular expression pattern to the beginning of a string.
fullmatch Match a regular expression pattern to all of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
compile Compile a pattern into a RegexObject.

www.leelasoft.com Page 10 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.

1.match() function:
 To check the given pattern at the beginning of the target string or not.
 If it is available, it returns the match object otherwise None.

 start(): start index of the match


 end(): end+1 index of the match
 group(): returns matched string

Example:
import re
s = input("Enter pattern to check:")
m = re.match(s, 'abaabaaab')

if m != None:
print("Match is available at the begining of the string")
print('Start Index:{} and End Index:{}'.format(m.start(),
m.end()))

else:
print("Match is not available at the begining of the string")

The search() Function


The search() function searches the string for a match, and returns a Match object if there is a
match.

If there is more than one match, only the first occurrence of the match will be returned:

Example: Search for the first white-space character in the string:


import re

txt = "The rain in Spain"


x = re.search("\s", txt)

print("The first white-space character is located in position:",


x.start())

Example:
import re

s=input("Enter pattern to check:")


m = re.search(s,'abaabaaab')

if m!= None:
print("Match is available")

www.leelasoft.com Page 11 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
print("First occurrence with start index:{} and end
index:{}".format(m.start(), m.end()))
else:
print("full string not matched")

The sub() Function


The sub() function replaces the matches with the text of your choice:

Example: Replace every white-space character with the number 9:


import re

#Replace all white-space characters with the digit "9":

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)

The findall() function:


The re.findall() method returns a list of strings containing all matches.

Example: Program to extract numbers from a string


import re

string = 'hello 12 hi 89. Howdy 34'


pattern = '\d+'

result = re.findall(pattern, string)


print(result)

Example: Print a list of all matches:


import re

#Return a list containing every occurrence of "ai":

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)

The finditer() function:


It scans <string> for non-overlapping matches of <regex> and returns an iterator that yields the
match objects from any it finds. It scans the search string from left to right and returns matches
in the order it finds them:

Example:
import re
matcher = re.finditer('ab', 'abaabaaba')
count = 0;

www.leelasoft.com Page 12 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
for m in matcher:
count += 1
print('start:{}, end:{}, group:{}'.format(m.start(), m.end(),
m.group()))

print('The number of occurrences:', count)


print(type(matcher))

Character Classes:
When we put the characters to be matched inside square brackets, we call it a character class.
For example, [aeiou] defines a character class that has a vowel character.

Placing a ^ at the start of a character. class causes it to match any character other than the ones
included.

Class Description
[abc] either a or b or c
[^abc] except a and b and c
[a-z] any lower case alphabet
[A-Z] any upper case alphabet
[a-zA-Z] any alphabet
[0-9] any digit
[a-zA-Z0-9] any alpha numeric character
[^a-zA-Z0-9] except alpha numeric character

import re

matcher = re.finditer('[abc]','a7b@k9z')

for m in matcher:
print(m.start(),'...',m.group())

Predefined Character classes:


Class Description
\s Space character
\S Except space character
\d any digits
\D except digits
\w any word character(alpha numeric character)
\W any character except word(i.e., special character)
. Every character

Example:
import re
matcher = re.finditer('\s','a7b @k9z')

www.leelasoft.com Page 13 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
for m in matcher:
print(m.start(),'...',m.group())

Example:
import re
matcher = re.finditer('\S','a7b @k9z')

for m in matcher:
print(m.start(),'...',m.group())

Application of Regular Expression


10 Digit Mobile Number:
[6789][0-9]{9}
[6-9]\d{9} #(a{9} a of 9times like \d)

import re

s=input("Enter mobile number:")


m = re.fullmatch('[6-9]\d{9}',s)

if m!= None:
print(s, "is valid mobile number")
else:
print(s, "is not valid mobile number")

Example #read numbers from a file


import re

f1=open('input.txt','r')
f2=open('output.txt','w')

for line in f1:


list = re.findall('[6-9]\d{9}',line)
for number in list:
f2.write(number+"\n")

f1.close()
f2.close()

Email Id check:
Example: For gmail:
import re
s = input("Enter mail id")
m = re.fullmatch('\w[a-zA-Z0-9_.]*@gmail[.]com', s)
if m != None:
print('Valid mail id')
else:
print('In valid mail id')

www.leelasoft.com Page 14 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
Example: For any Mail:
import re
s=input("Enter mail id")
m = re.fullmatch('\w[a-zA-Z0-9_.]*@[a-z0-9]+[.][a-z]+',s)
if m!=None:
print('Valid mail id')
else:
print('In valid mail id')

Example: For any gmail or rediff Mail:


import re
s=input("Enter mail id")
m = re.fullmatch('\w[a-zA-Z0-9_.]*@(gmail | rediffmail)[.]com',s)
if m!=None:
print('Valid mail id')
else:
print('In valid mail id')

Data Structures:
A data structure is a group of data elements that are put together under one name. Data
structure defines a particular way of storing and organizing data in a computer so that it can be
used efficiently.

Sequence
Sequence is the most basic data structure in Python. In the sequence data structure, each
element has a specific index. This index value starts from zero and is automatically incremented
for the next element in the sequence. In Python, sequence is the generic term for an ordered set.
For example, we have already studied strings which are a sequence of characters.

Python has some basic built-in functions that help programmers to manipulate elements that
form a part of a sequence. These functions include finding the length of a sequence, finding the
largest and smallest elements in a sequence, etc. Other operations that can be performed on a
sequence include indexing, slicing, adding, multiplying, and checking for membership.

Lists in Python-3
A list is a collection of arbitrary objects.

Lists are just like the arrays, declared in other languages. But lists are allowed Heterogeneous
and Homogeneous elements like Integers, Strings, as well as Objects.

Lists are mutable, and hence, they can be altered even after their creation.

The characteristics of lists:


1. Lists are ordered.
2. Lists can contain any arbitrary objects.
3. List elements can be accessed by index.

www.leelasoft.com Page 15 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
4. Lists can be nested to arbitrary depth.
5. Lists are mutable.
6. Lists are dynamic.

Create a lists in Python:


Lists are defined in Python by enclosing a comma-separated sequence of objects in square
brackets '[]' and by using list() built-in function.

By using []:
names = ["Kajal", "Katrina", "Samantha"]
cities = ["BZA", "TPG", "VSKP"]

By Using list():
Syntax:
<var_name> = list([iterable])

Examples:
a = list("Leela Soft")
b = list([10,20,30])
c = list((10,20,30))
d = list(range(5))
e = list(range(1,21,2))

ex:
>>> a = list(10)
TypeError: 'int' object is not iterable

Lists Are Ordered:


Examples:
a = ['foo', 'bar', 'baz', 'qux']
b = ['baz', 'qux', 'bar', 'foo']

Case1: a == b #False

case2: a is b #False

Case3: [1, 2, 3, 4] == [4, 1, 3, 2] #False

>>> [] == []
True
>>> [1,2] == [1,2]
True

Lists Can Contain Arbitrary Objects:


The elements of a list can all be the same type:
Ex: a = [2, 4, 6, 8]

The elements can be of varying types:


Ex: a = [10, 20.20, "Leela Soft", 20+30j]

www.leelasoft.com Page 16 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

A list can contain any number of objects:


for i in list(range(100000)):
print(i)

List elements can be accessed by using index:


Individual elements in a list can be accessed by using an index in square
brackets.

List indexing is zero-based as it is with strings.

Example:
li = [10,20,30,40,50]

Python code to access some elements of li:


>>>li[1]
20

>>>li[2]
30

>>>li[5] #if we give index as out of range


IndexError: list index out of range

A negative list index counts from the end of the list:


>>>a[-2]
40

Slicing:
Slicing also works. If 'li' is a list, the expression li[m:n] returns
the portion of 'li' from index m to, index (n-1):

>>>li[1:4]
[20,30,40]

Note: start index is low and end index is high.

Lists can be nested to arbitrary depth:


A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary
depth.

>>>li=[10,20, [100,200], 30, [300,400,[1000,2000],500] ,40]

>>>li[2][1]
200
>>>li[4][2][1]
2000

Note: To access the items in a sublist, simply append an additional index:

www.leelasoft.com Page 17 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

Note: There is no limit, short of the extent of our computer’s memory, to the depth or complexity
with which lists can be nested in this way.

Note: All the usual syntax regarding indices and slicing applies to sublists as well.

len(s) Built-In Function:


Return the length (the number of items) of an object. The argument 's' may be a sequence (such
as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Examples:
>>> len(li)
6

>>> len(li[2]) #li[2] is sublist


2

Lists are mutable:


The list is the mutable data type. Once a list has been created, elements can be added, deleted,
shifted, and moved around at will.

Modifying a Single List Value:


A single value in a list can be replaced by indexing and simple assignment:

>>>li = [10,20,30]
>>>li[2] = 300
>>>li #it prints modified list
[10,20,300]

Modifying Multiple List Values:


If we want to change several contiguous elements in a list at one time, in Python allows this with
slice assignment.

Syntax:
li[m:n] = <iterable>
This assignment replaces the specified slice of 'li' with <iterable>:

Example:
>>>li = [10,20,30,40,50]
>>>li[1:4]=[100,200,300]
>>>li
[10, 100, 200, 300, 50]

Example:
>>>li = [10,20,30,40,50]
>>>li[1:4]="Leela"
>>>li
[10, 'L', 'e', 'e', 'l', 'a', 50]

www.leelasoft.com Page 18 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
Note:
The number of elements inserted need not be equal to the number replaced. Python just grows
or shrinks the list as needed.

We can insert multiple elements in place of a single element—just use a slice that denotes only
one element:

Example:
>>> li = [1, 2, 3]
>>> li[1:2] = [2.1, 2.2, 2.3]
>>> li
[1, 2.1, 2.2, 2.3, 3]

Note:
This is not the same as replacing the single element with a list:

>>> li = [1, 2, 3]
>>> li[1] = [2.1, 2.2, 2.3]
>>> li
[1, [2.1, 2.2, 2.3], 3]

We can also insert elements into a list without removing anything. Simply
specify a slice of the form [n:n] (a zero-length slice) at the desired
index:

>>> li = [1, 2, 7, 8]
>>> li[2:2] = [3, 4, 5, 6]
>>> li
[1, 2, 3, 4, 5, 6, 7, 8]

We can delete multiple elements out of the middle of a list by assigning


the appropriate slice to an empty list.

>>>li = [10,20,30,40,50]
>>>li[1:4]=[]
>>>li
[10, 50]

We can also use the del statement with the same slice:
The del statement:
There is a way to remove an item from a list given its index instead of
its value: the del statement.

The del statement can also be used to remove slices from a list or clear
the entire list.

Example:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]

www.leelasoft.com Page 19 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
>>> a
[1, 66.25, 333, 333, 1234.5]

>>> del a[2:4]


>>> a
[1, 66.25, 1234.5]

>>> del a[:]


>>> a
[]

del can also be used to delete entire variables:


>>> del a

Referencing the name 'a' hereafter is an error i.e,


NameError: name 'a' is not defined

Lists are dynamic:


When items are added to a list, it grows as needed:

>>>a = [10,20,30,10,50]
>>>a[3:3] = ["Chiru", "Nag", "Balayya", "Venky"]
>>>a
[10,20,30,"Chiru", "Nag", "Balayya", "Venky",10,50]

Similarly, a list shrinks to accommodate the removal of items:


>>>a
[10,20,30,"Chiru", "Nag", "Balayya", "Venky",10,50]

>>>a[2:5] = []
>>>a
[10,20, "Balayya", "Venky",10,50]

>>>del a[3]
[10,20, "Balayya", 10,50]

Methods in List Class:


append(self, object, /)
Append object to the end of the list.

>>>li = [10]
>>>li.append(20)
>>>li
[10,20]

>>> a =[100,200]
>>> li.append(a)
>>> li

www.leelasoft.com Page 20 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
[10, 20, [100, 200]]

>>> a=1000
>>> li.append(a)
>>> li
[10, 20, [100, 200], 1000]

extend(self, iterable, /)
Extend list by appending elements from the iterable.

>>>li = [10]
>>> a =[100,200]
>>> li.extend(a)
>>> li
[10, 100, 200]

insert(self, index, object, /)


Insert object before index.

>>> li=[]
>>> li.insert(1,100)
>>> li
[100]
>>> li
[100]
>>> li.insert(1,100)
>>> li
[100, 100]
>>> li.insert(1,1000)
>>> li
[100, 1000, 100]
>>> li.insert(6,10012)
>>> li
[100, 1000, 100, 10012]

clear(self, /)
Remove all items from list.

>>> li.clear()
>>> li
[]

copy(self, /)
Return a shallow copy of the list.

>>> li = [100, 1000, 100]


>>> a = li.copy()
>>> a
[100, 1000, 100]

www.leelasoft.com Page 21 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

>>> a.append(2000)
>>> a
[100, 1000, 100, 2000]

>>> li
[100, 1000, 100]

count(self, value, /)
Return number of occurrences of value.

>>> li = [10,20,30,10,20,10]
>>> li.count(10)
3
>>> li.count(100)
0

index(self, value, start=0, stop=2147483647, /)


Return first index of value.
Raises ValueError if the value is not present.

>>> li = [10, 20, 30, 40, 50, 10, 20, 10]


>>> li.index(10)
0

>>> li.index(100)
ValueError: 100 is not in list

>>> li.index(20)
1

>>> li.index(50)
4

pop(self, index=-1, /)
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.

>>> li = [10, 20, 30, 40, 50, 10, 20, 10]


>>> li.pop(1)
20
>>> li
[10, 30, 40, 50, 10, 20, 10]

>>> li.pop()
10
>>> li
[10, 30, 40, 50, 10, 20]

www.leelasoft.com Page 22 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
>>> li.pop()
20
>>> li
[10, 30, 40, 50, 10]

>>> li.pop(100)
IndexError: pop index out of range

remove(self, value, /)
Remove first occurrence of value.
Raises ValueError if the value is not present.

>>> li = [10, 30, 40, 50, 10]


>>> li.remove(10)
>>> li
[30, 40, 50, 10]

>>> li.remove(100)
ValueError: list.remove(x): x not in list

>>> li.remove()
TypeError: remove() takes exactly one argument (0 given)

reverse(self, /)
Reverse *IN PLACE*.

>>> li = [50,20,10,30,40,90,60,70,80]
>>> li
[50, 20, 10, 30, 40, 90, 60, 70, 80]

>>> li.reverse()
>>> li
[80, 70, 60, 90, 40, 30, 10, 20, 50]
>>>

sort(self, /, *, key=None, reverse=False)


Stable sort *IN PLACE*.

>>> li.sort() #by default ascending order


>>> li
[10, 20, 30, 40, 50, 60, 70, 80, 90]

>>> li = [50,20,10,30,40,90,60,70,80]
>>> li
[50, 20, 10, 30, 40, 90, 60, 70, 80]

>>> li.sort(reverse=True) #descending order


>>> li
[90, 80, 70, 60, 50, 40, 30, 20, 10]

www.leelasoft.com Page 23 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu

Functional Programming
Functional programming decomposes a problem into a set of functions. The map(), filter(), and
reduce() functions which we will discuss in this section form a part of functional programming
tools that work on all list items. However, it is recommended to use list comprehensions instead
of these functions where possible.

filter() Function
The filter() function constructs a list from those elements of the list for which a function returns
True.

The syntax of the filter() function is given as,


filter (function, sequence)

Q. Program to filter only even numbers from the list by using filter() function?
Without lambda Function:
def isEven(x):
if x % 2 == 0:
return True
else:
return False

l = [0, 5, 10, 15, 20, 25, 30]


l1 = list(filter(isEven, l))
print(l1) # [0,10,20,30]

With lambda Function:


l=[0,5,10,15,20,25,30]

l1=list(filter(lambda x:x%2==0,l))
print(l1) #[0,10,20,30]

l2=list(filter(lambda x:x%2!=0,l))
print(l2) #[5,15,25]

map() function:
For every element present in the given sequence, apply some functionality and generate new
element with the required modification. For this requirement we should go for map() function.

Syntax: map(function, sequence)


The function can be applied on each element of sequence and generates new sequence.

Example: For every element present in the list perform double and generate new list of doubles.
Example: Without lambda
l=[1,2,3,4,5]

www.leelasoft.com Page 24 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
def doubleIt(x):
return 2*x

l1=list(map(doubleIt,l))
print(l1) #[2, 4, 6, 8, 10]

Example: with lambda


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

l1=list(map(lambda x:2*x,l))
print(l1) #[2, 4, 6, 8, 10]

Example 2: To find square of given numbers


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

l1=list(map(lambda x:x*x,l))
print(l1) #[1, 4, 9, 16, 25]

We can apply map() function on multiple lists also. But make sure all list should have same
length.

Syntax: map(lambda x,y:x*y,l1,l2))


Here, x is from l1 and y is from l2

Example:
l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3) #[2, 6, 12, 20]

reduce() function:
The reduce() function reduces sequence of elements into a single element by applying the
specified function.

Syntax: reduce(function, sequence)

The reduce() function present in functools module and hence we should write import
statement to import that module.

Example:
from functools import reduce

l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result) # 150

www.leelasoft.com Page 25 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
Example:
from functools import reduce

l=[10,20,30,40,50]
result=reduce(lambda x,y:x*y,l)
print(result) #12000000

Example:
from functools import reduce

result = reduce(lambda x, y:x + y, range(1, 101))


print(result) # 5050

Python Tuple Methods


Python has two built-in methods that you can use on tuples.

Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was
found

Python Tuple count() Method


Example: Return the number of times the value 5 appears in the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.count(5)

print(x)

Python Tuple index() Method


Example: Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)

Python Set Methods:


Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or
more sets

www.leelasoft.com Page 26 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
difference_update() Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable

Python Set add() Method


Example: Add an element to the fruits set:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)

Python Set clear() Method


Example: Remove all elements from the fruits set:
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)

Python Set copy() Method


Example: Copy the fruits set:
fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)

Python Set difference() Method


Example: Return a set that contains the items that only exist in
set x, and not in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.difference(y)
print(z)

Python Set difference_update() Method


Example: Remove the items that exist in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

www.leelasoft.com Page 27 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
x.difference_update(y)
print(x)

Python Set discard() Method


Example: Remove "banana" from the set:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)

Python Set intersection() Method


Example: Return a set that contains the items that exist in both
set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

Python Set intersection_update() Method


Example: Remove the items that is not present in both x and y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)
print(x)

Python Set issubset() Method


Example: Return True if all items in set x are present in set y:
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}

z = x.issubset(y)
print(z)

Python Set issuperset() Method


Example: Return True if all items set y are present in set x:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}

z = x.issuperset(y)
print(z)

Python Set pop() Method


Example: Remove a random item from the set:
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits)

Python Set remove() Method


Example: Remove "banana" from the set:

www.leelasoft.com Page 28 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)

Python Set union() Method


Example: Return a set that contains all items from both sets,
duplicates are excluded:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.union(y)
print(z)

Python Dictionary Methods


Python has a set of built-in methods that we can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

Python Dictionary clear() Method


Example: Remove all elements from the car list:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.clear()
print(car)

Python Dictionary pop() Method


Example: Remove "model" from the dictionary:

car = {
"brand": "Ford",
"model": "Mustang",

www.leelasoft.com Page 29 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
"year": 1964
}

car.pop("model")
print(car)

Python Dictionary popitem() Method


Example: Remove the last item from the dictionary:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.popitem()
print(car)

Python Dictionary get() Method


Example: Get the value of the "model" item:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.get("model")
print(x)

Python Dictionary items() Method


Example: Return the dictionary's key-value pairs:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()
print(x)

Python Dictionary keys() Method


Example: Return the keys:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

www.leelasoft.com Page 30 of 31 Cell: 78 42 66 47 66


Leela Soft Python Madhu
}

x = car.keys()
print(x)

Python Dictionary values() Method


Example Return the values:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()
print(x)

Python Dictionary copy() Method


Example: Copy the car dictionary:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.copy()
print(x)

www.leelasoft.com Page 31 of 31 Cell: 78 42 66 47 66

You might also like