Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Unit II Python Strings

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit II Python Strings

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 73

Fergusson College

Ashoka Education Foundation


Established
Ashoka Center for Business in
and Computer Studies, Nashik
2009
ISO 9001 : 2015 | Certificate No. : QM 01 00652 | Minority Institute

Unit II –
Python String

Mr. Rahul Sonawane


website: http://www.aef.edu.in/acbcs/
Content
Fergusson College
•Concept, escape characters
•String special operations
•String formatting operator
•Single quotes, Double quotes, Triple quotes
•Raw String, Unicode strings, Built-in String methods
•Python Lists - concept, creating and accessing elements, updating & deleting
lists, basic list operations, reverse
•Indexing, slicing and Matrices
•built-in List functions
•Functional programming tools - filter(), map(), and reduce()
•Using Lists as stacks and Queues, List comprehensions

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Python Strings
Fergusson College
• Text is represented in programs by the string data type.
• A string is a sequence of characters enclosed within quotation marks
(") or apostrophes (').
• Strings are amongst the most popular types in Python. We can create
them simply by enclosing characters in quotes.
• Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a variable.
For example
var1= 'Hello World!'
var2 = "Python Programming"

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Python Strings
Fergusson College
• Getting a string as input

>>> firstName = input("Please enter your name: ")


Please enter your name: MSC
>>> print("Hello", firstName)
Hello MSC

• Notice that the input is not evaluated. We want to store the typed
characters, not to evaluate them as a Python expression.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Accessing Values
Fergusson in Strings
College
• We can access the individual characters in a string through indexing.
• The positions in a string are numbered from the left, starting with 0.
• The general form is <string>[<expr>], where the value of expr determines which character is
selected from the string.
• Python does not support a character type; these are treated as strings of length one, thus
also considered a substring.
• To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
• For example-
#!/usr/bin/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result
var1[0]: H
var2[1:5]: ytho

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Accessing Values
Fergusson in Strings
College
H e l l o B o b

0 1 2 3 4 5 6 7
8 greet = "Hello Bob"
>>>
>>> greet[0]
'H'
>>> print(greet[0], greet[2], greet[4])
Hlo
>>> x = 8
>>> print(greet[x - 2])
B

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Accessing Values
Fergusson in Strings
College
H e l l o B o b

0 1 2 3 4 5 6 7
•8 In a string of n characters, the last character is at position n-
1 since we start counting with 0.
• We can index from the right side using negative indexes.
>>> greet[-1]
'b'
>>> greet[-3]
'B'

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Accessing Values
Fergusson in Strings
College
•Indexing returns a string containing a single character from
a larger string.
•We can also access a contiguous sequence of characters,
called a substring, through a process called slicing.

Slicing:
<string>[<start>:<end>]

•start and end should both be ints

•The slice contains the substring beginning at position start


and runs up to but doesn’t include the position end.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Accessing Values
Fergusson in Strings
College
H e l l o B o b

0 1 2 3 4 5 6 7
8
>>> greet[0:3]
'Hel'
>>> greet[5:9]
' Bob'
>>> greet[:5]
'Hello'
>>> greet[5:]
' Bob'
>>> greet[:]
'Hello Bob'

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Slicing
Fergusson College
• To obtain a substring
• s[start:end] means substring of s starting at index
start and ending at index end-1
• s[0:len(s)] is same as s
• Both start and end are optional
– If start is omitted, it defaults to 0
– If end is omitted, it defaults to the length of string
• s[:] is same as s[0:len(s)], that is same as s

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Slicing
Fergusson College

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


More Slicing
Fergusson College

Understanding Indices for slicing


A c a d s
0 1 2 3 4 5
-5 -4 -3 -2 -1
12
Welcome Python Programming
M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane
Out ofFergusson
Range Slicing
College 0
A
1
c
2
a d
3 4
s

-5 -4 -3 -2 -1
• Out of range indices are ignored for slicing
• when start and end have the same sign, if start >=end,
empty slice is returned
Why?

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Updating Strings
Fergusson College
• You can "update" an existing string by (re)assigning a variable to
another string.
• The new value can be related to its previous value or to a completely
different string altogether.
• For example-
#!/usr/bin/python3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
• When the above code is executed, it produces the following result-
Updated String :- Hello Python

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Short Quiz College
Fergusson
• What is printed by the following statements?
s = "python is awesome"
print(s[2] + s[-5])

a) Run time crash/error

b) o

c) te The correct answer is


te

d) tw

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Short Quiz College
Fergusson
• What is printed by the following statements?
s = "python rocks"
print(s[7:11] * 3)

a) rockrockrock

b) rocksrocksrocks

c) rock rock rock The correct answer is


a

d) error

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Escape Characters
Fergusson College
• Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
• An escape character gets interpreted; in a single quoted as well as double quoted strings.
Form feed Escape Character
Code Description To escape form feed character, use a preceding backslash for
character ‘f’ in the string.
\’ Single Quote
x = 'hello\fworld'
\” Double Quote print(x)

\\ Backslash Output
hello world
\n New Line Octal Value Escape Character
To escape a byte of octal value character, use a preceding backslash
\r Carriage Return for three digit octal value in the string.
x = '\101\102\103'
\t Tab print(x)
Output
\b Backspace ABC

\f Form Feed Octal value 101 represents A, 102 represents B, and so on. So, in
the output, we got ABC for the given octal values.
\ooo Octal Value
Hex Value Escape Character
\xhh Hex Value To specify a byte using hex value, use a preceding backslash and x for two
digit hex value in the string.
x = '\x41\x42\x43'
print(x)
Output
ABC
Hex value of 41 means 65 in decimal. And a byte with decimal 65
represents the character A. Similarly 42 is B, 43 is C.
M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane
String Special College
Fergusson Operators
• Assume string variable a holds 'Hello' and variable b holds 'Python',
then-

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Special College
Fergusson Operators
• Assume string variable a holds 'Hello' and variable b holds 'Python',
then-

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Formatting
Fergusson Operator
College
• One of Python's coolest features is the string format operator %.
• This operator is unique to strings and makes up for the pack of
having functions from C's printf() family.
• Following is a simple example −
#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % (‘Rahul', 88))
• When the above code is executed, it produces the following result −
My name is Rahul and weight is 88 kg!

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Formatting
Fergusson Operator
College
• Here is the list of complete set of symbols which can be used along with %-

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Formatting
Fergusson Operator
College
• Here is the list of complete set of symbols which can be used along with %-

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Formatting
Fergusson Operator
College
• Other supported symbols and functionality are listed in the following table-

>>> '%d' % 100


'100'
>>> '%d' % 0b1111
'15'
>>> "%s" % 'foo'
'foo'

>>> "%d" % 1
'1'
>>> "%-5d" % 1
'1 ‘

>>> "%x" % 17
'11'
>> "%#x" % 17
'0x11'
>>> "%#X" % 17
'0X11'
>>> "%d" % 1
'1'
>>> "%03d" % 1
'001'

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Formatting
Fergusson Operator
College
• Other supported symbols and functionality are listed in the following table-

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Built-in StringCollege
Fergusson Methods
• Python includes the following built-in methods to manipulate strings-
• String capitalize() Method
It returns a copy of the string with only its first character capitalized.
Syntax
str.capitalize()
Parameters
NA
Return Value
string
Example
#!/usr/bin/python3
str = "this is string example....!!!"
print ("str.capitalize() : ", str.capitalize())
Result
str.capitalize() : This is string example....!!!

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Built-in StringCollege
Fergusson Methods
• Python includes the following built-in methods to manipulate strings-
• String center() Method
• The method center() returns centered in a string of length width. Padding is done using the
specified fillchar. Default filler is a space.
• Syntax
str.center(width[, fillchar])
• Parameters
– width - This is the total width of the string. Example
– fillchar - This is the filler character. The following example shows the usage of
• the center() method.
Return Value
#!/usr/bin/python3
– This method returns a string that is at least width
str = "this is string example....wow!!!“
characters wide, created by padding the
print ("str.center(40, 'a') : ", str.center(40, 'a'))
– string with the character fillchar (default is a space).

Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Built-in StringCollege
Fergusson Methods
• String count() Method
• Description
– The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional
arguments start and end are interpreted as in slice notation.
• Syntax
– str.count(sub, start= 0,end=len(string))
• Parameters
• sub - This is the substring to be searched.
• start - Search starts from this index. First character starts from 0 index. By default search starts
from 0 index.
• end - Search ends from this index. First character starts from 0 index. By default search ends at
the last index.
Example
• Return Value #!/usr/bin/python3
• Centered in a string of length width. str="this is string example....wow!!!"
sub='i'
print ("str.count('i') : ", str.count(sub))
Result sub='exam'
print ("str.count('exam', 10, 40) : ",
str.count('i') : 3
str.count(sub,10,40))
str.count('exam', 4, 40) ):

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String endswith()
Fergusson Method
College
• Description
– It returns True if the string ends with the specified suffix, otherwise return False optionally
restricting the matching with the given indices start and end.
• Syntax
str.endswith(suffix[, start[, end]])
• Parameters
– suffix - This could be a string or could also be a tuple of suffixes to look for.
– start - The slice begins from here.
– end - The slice ends here.
• Return Value
• TRUE if the string ends with the specified suffix, otherwise FALSE.
Example
Str='this is string example....wow!!!'
Result suffix='!!'
True print (Str.endswith(suffix))
True print (Str.endswith(suffix,20))
False suffix='exam'
True print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String find()College
Fergusson Method
• Description
– The find() method determines if the string str occurs in string, or in a substring of string if the
starting index beg and ending index end are given.
• Syntax
str.find(str, beg=0 end=len(string))
• Parameters
– str - This specifies the string to be searched.
– beg - This is the starting index, by default its 0.
– end - This is the ending index, by default its equal to the lenght of the string.
• Return Value
• Index if found and -1 otherwise.

#!/usr/bin/python3
Result str1 = "this is string example....wow!!!"
15 str2 = "exam";
15 print (str1.find(str2))
-1 print (str1.find(str2, 10))
print (str1.find(str2, 40))

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String index()College
Fergusson Method
• Description
– The index() method determines if the string str occurs in string or in a substring of string, if the
starting index beg and ending index end are given.
– This method is same as find(), but raises an exception if sub is not found.
• Syntax
str.index(str, beg=0 end=len(string))
• Parameters
– str - This specifies the string to be searched.
– beg - This is the starting index, by default its 0.
– end - This is the ending index, by default its equal to the length of the string.
• Return Value
• Index if found otherwise raises an exception if str is not found.
Result Example
15 #!/usr/bin/python3
15 str1 = "this is string example....wow!!!"
Traceback (most recent call last): str2 = "exam";
File "test.py", line 7, in
print (str1.index(str2))
print (str1.index(str2, 40))
ValueError: substring not found
print (str1.index(str2, 10))
shell returned 1 print (str1.index(str2, 40))

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String len() College
Fergusson Method
• Description
– The len() method returns the length of the string.
• Syntax
– len( str )
• Parameters
– NA
• Return Value
– This method returns the length of the string.

• Example
• The following example shows the usage of len() method.
• #!/usr/bin/python3
Result
• str = "this is string example....wow!!!"
Length of the string: 32
• print ("Length of the string: ", len(str))a

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String replace()
Fergusson Method
College
• Description
– The replace() method returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max.
• Syntax
– str.replace(old, new[, max])
• Parameters
– old - This is old substring to be replaced.
– new - This is new substring, which would replace old substring.
– max - If this optional argument max is given, only the first count occurrences are replaced.
• Return Value
– This method returns a copy of the string with all occurrences of substring old replaced bynew. If the
optional argument max is given, only the first count occurrences are replaced.
Example
Result
#!/usr/bin/python3
thwas was string example....wow!!! thwas
str = "this is string example....wow!!! this is really string"
was really string
print (str.replace("is", "was"))
thwas was string example....wow!!! thwas
print (str.replace("is", "was", 3))
is really string

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String split()College
Fergusson Method
• Description
– The split() method returns a list of all the words in the string, using str as the separator
(splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
• Syntax
– str.split(str="", num=string.count(str)).
• Parameters
– str - This is any delimeter, by default it is space.
– num - this is number of lines to be made
• Return Value
– This method returns a list of lines.

Example
#!/usr/bin/python3 Result
str = "this is string example....wow!!!" ['this', 'is', 'string', 'example....wow!!!']
print (str.split( )) ['th', 's is string example....wow!!!']
print (str.split('i',1)) ['this is string example....', 'o', '!!!']
print (str.split('w'))

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Method
Fergusson College
• String isalnum() Method
• Description: The isalnum() method checks whether the string consists of alphanumeric characters.
• Syntax
– str.isalnum()
• Parameters
– NA
• Return Value
– This method returns true if all the characters in the string are alphanumeric and there is at least one character,
false otherwise.
• String isalpha() Method
• Description:The isalpha() method checks whether the string consists of alphabetic characters only.
• Syntax
– str.isalpha()
• Parameters
– NA
• Return Value
– This method returns true if all the characters in the string are alphabetic and there is at least one character, false
otherwise.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Method
Fergusson College
• String isdigit() Method
• Description: The method isdigit() checks whether the string consists of digits only.
• Syntax
– str.isdigit()
• Parameters
– NA
• Return Value
– This method returns true if all characters in the string are digits and there is at least one character, false
otherwise.
• String islower() Method
• Description: The islower() method checks whether all the case-based characters (letters) of the string are
lowercase.
• Syntax
– str.islower()
• Parameters
– NA
• Return Value
– This method returns true if all cased characters in the string are lowercase and there is at least one cased
character, false otherwise.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Method
Fergusson College
• String isupper() Method
• Description -The isupper() method checks whether all the case-based characters (letters)
of the string are uppercase.

• String isnumeric() Method


• Description- The isnumeric() method checks whether the string consists of only numeric
characters. This method is present only on unicode objects.

• String isspace() Method


• Description- The isspace() method checks whether the string consists of whitespace.

• String istitle() Method


• Description- The istitle() method checks whether all the case-based characters in the string
following non-casebased letters are uppercase and all other case-based characters are
lowercase.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


String Method
Fergusson College
• String join() Method
• Description- The join() method returns a string in which the string elements of sequence
have been joined by str separator.

• String lower() Method


• Description- The method lower() returns a copy of the string in which all case-based characters
have been lowercased.

• String max() Method


• Description- The max() method returns the max alphabetical character from the string str.

• String min() Method


• Description- The min() method returns the min alphabetical character from the string str.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Examples
Fergusson College
• Create a string made of the first, middle and last character

Solution:
str1 = ‘Computer'
print("Original String is", str1)
res = str1[0]
l = len(str1)
mi = int(l / 2)
res = res + str1[mi]
res = res + str1[l - 1]
print("New String:", res)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Examples
Fergusson College
• Arrange string characters such that lowercase letters should
come first
Solution:
str1 = “NaShIk"
print('Original String:', str1)
lower = []
upper = []
for char in str1:
if char.islower():
lower.append(char)
else:
upper.append(char)
sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Examples
Fergusson College
• Count all letters, digits, and special symbols from a given string
Solution:
sample_str = "P@th2o&#5n"
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
else:
symbol_count += 1
print("Chars =", char_count, "Digits =", digit_count,
"Symbol =", symbol_count)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Examples
Fergusson College
• Create a mixed String using the following rules
• Given two strings, s1 and s2. Write a program to create a new string
s3 made of the first char of s1, then the last char of s2, Next, the
second char of s1 and second last char of s2, and so on. Any leftover
chars go at the end of the result.

Calculate the sum and average of the digits present in a string

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


ListCollege
Fergusson
• The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth.
• Python has six built-in types of sequences, but the most common ones are lists and
tuples.
• List is a collection which is ordered and mutable.
• Allows duplicate members.
• A List can have elements of different datatypes
• A list contains items separated by commas and enclosed within square brackets
([]).
• Example:
myList=[10,34,45,12,67]
Colors= [“Red”, “Green”, “Blue”, “Yellow”]
list1= [123, “Asha”]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


42
ListCollege
Fergusson
• Example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


print (list) # Prints complete list
#Output:
#['abcd', 786, 2.23, 'john', 70.2]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


43
Accessing Values
Fergusson in Lists
College
• To access values in lists, use the square brackets for slicing
along with the index or indices to obtain value available at that
index.
• The values stored in a list can be accessed using the slice
operator ([ ] and [:])
• Example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


print (list[0]) # Prints first element of the list
#Output:
#abcd

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


44
Accessing Values
Fergusson in Lists
College
• Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print (list[1:3]) # Prints elements starting from 2nd till 3rd
Output:
[786, 2.23]

• Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print (list[2:]) # Prints elements starting from 3rd element
#Output:
#[2.23, 'john', 70.2]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


45
Accessing Values
Fergusson in Lists
College
• The asterisk (*) is the repetition operator.
• Example
mylist = [123, ‘Reeta']
print (mylist * 2) # Prints list two times
#Output:
#[123, ‘Reeta‘, 123, ‘Reeta']

• The plus (+) sign is the list concatenation operator


• Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
mylist = [123, ‘Reeta']
print (list + mylist) # Prints concatenated lists
#Output:
[ 'abcd', 786 , 2.23, 'john', 70.2 , 123, ‘Reeta‘]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


46
ListCollege
Fergusson
• Lists can be nested
Example:

l1=[1,2,[4,4,5]]
print l1
#Output: [1, 2, [4, 4, 5]]

nestedList = [1, 2, ['a', 1], 3]


subList = nestedList[2]
# access the first element inside the inner list:
element = nestedList[2][0]
print("List inside the nested list: ", subList)
print("First element of the sublist: ", element)

Output
List inside the nested list: ['a', 1] First
element of the sublist: a

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


47
Delete List Elements
Fergusson College
• To remove a list element, you can use either the del statement if
you know exactly which element(s) you are deleting.
• You can use the remove() method if you do not know exactly which
items to delete.
• For example-
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)

Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics',
'chemistry', 2000]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Indexing, SlicingCollege
Fergusson and Matrixes
• Since lists are sequences, indexing and slicing work the same way
for lists as they do for strings.
• Assuming the following input-
• L=['C++'', 'Java', 'Python']

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Creating a College
Fergusson matrix
• Creating a matrix is one of the most useful applications of nested lists. This is done
by creating a nested list that only has other lists of equal length as elements.
• The number of elements in the nested lists is equal to the number of rows of the
matrix.
• The length of the lists inside the nested list is equal to the number of columns.
• Thus, each element of the nested list (matrix) will have two indices: the row and the
column.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Creating a College
Fergusson matrix
# create matrix of size 4 x 3
matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

rows = len(matrix) # no of rows is no of sublists i.e. len of list


cols = len(matrix[0]) # no of cols is len of sublist # printing matrix
print("matrix: ")
for i in range(0, rows): Output
print(matrix[i])
matrix:
# accessing the element on row 2 and column 1 i.e. 3 [0, 1, 2]
[3, 4, 5]
print("element on row 2 and column 1: ", matrix[1][0]) [6, 7, 8]
# accessing the element on row 3 and column 2 i.e. 7 [9, 10, 11]
element on row 2 and column 1
print("element on row 3 and column 2: ", matrix[2][1]) element on row 3 and column 2

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Basic List Operations
Fergusson College
• Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List is mutable
Fergusson College
• Can change content without changing the identity.
Example:
my_list = [100, 200, 300]
my_list[0] = 40
print(my_list)

Output:
[40, 200, 300]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


53
List Comprehension
Fergusson College
• List comprehension is an elegant way to define and
create lists
• Syntax:
new_list = [expression for member in iterable]
–Example:
list= [letter for letter in "human"]
print (list)
#Output:
# ['h', 'u', 'm', 'a', 'n']

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


54
List Comprehension
Fergusson College
• Example: List of all numbers from 0 to 9

list= [x for x in range(10)]


print (list)
#Output:
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


55
ListCollege
Fergusson
• Example: List of even numbers form 0 to 10

list= [x for x in range(10) if x % 2 == 0]


print (list)
#Output
# [0, 2, 4, 6, 8]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


56
Example
Fergusson College
• Write a program that prints out all the elements of the list that are less
than 10.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]


for i in a:
if i < 10:
print(i)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List len() Method
Fergusson College
• Description: The len() method returns the number of elements in the list.
• Syntax
– len(list)
• Parameters
– list - This is a list for which, number of elements are to be counted.
• Return Value
– This method returns the number of elements in the list.

Example
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
list2=list(range(5)) #creates list of numbers between 0-4
print (len(list2))
When we run above program, it produces
following result-
3
5

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List max() Method
Fergusson College
• Description
– The max() method returns the elements from the list with maximum value.
• Syntax
– max(list)
• Parameters
– list - This is a list from which max valued element are to be returned.
• Return Value
– This method returns the elements from the list with maximum value.

Example
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
When we run above program, it produces
following result-
Max value element : Python
Max value element : 700

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List min() Method
Fergusson College
• Description
– The method min() returns the elements from the list with minimum value.
• Syntax
– min(list)
• Parameters
– list - This is a list from which min valued element is to be returned.
• Return Value
– This method returns the elements from the list with minimum value.

Example
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
When we run above program, it produces
following result
min value element : C++
min value element : 200

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List list() Method
Fergusson College
• Description
– The list() method takes sequence types and converts them to lists. This is used to convert a
given tuple into list.
• Note: Tuple are very similar to lists with only difference that element values
of a tuple can not be changed and tuple elements are put between parentheses
instead of square bracket.
• This function also converts characters in a string into a list.
• Syntax
– list(seq ) Example
#!/usr/bin/python3
• Parameters
aTuple = (123, 'C++', 'Java', 'Python
– seq - This is a tuple or string to be converted into list. list1 = list(aTuple)
• Return Value print ("List elements : ", list1)
– This method returns the list. str="Hello World"
list2=list(str)
OutPut: print ("List elements : ", list2)
List elements : [123, 'C++', 'Java', 'Python']
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List Methods
Fergusson College
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


62
Examples
Fergusson College
• Reverse a list in Python
list function reverse()

list1 = [100, 200, 300, 400, 500]


list1.reverse()
print(list1)

Using negative slicing


-1 indicates to start from the last item.

list1 = [100, 200, 300, 400, 500]


list1 = list1[::-1]
print(list1)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List Methods
Fergusson College
• The extend method adds elements from another list, or
other iterable
>>> a = [11, 22, 33, 44, ]
>>> b = [55, 66]
>>> a.extend(b)
>>> a
[11, 22, 33, 44, 55, 66]
• Use the append method on a list to add/append an item to the end of a list:
>>> a = ['aa', 11]
>>> a.append('bb')
>>> a.append(22)
>>> a
['aa', 11, 'bb', 22]

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List Methods
Fergusson College
• The insert method on a list enables us to insert items at a given position in a list:
>>> a = [11, 22, 33, 44, ]
>>> a.insert(0, 'aa')
>>> a
['aa', 11, 22, 33, 44]
>>> a.insert(2, 'bb')
>>> a
['aa', 11, 'bb', 22, 33, 44]
But, note that we use append to add items at the end of a list.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


List Methods
Fergusson College
• The pop method on a list returns the "rightmost” item from a list and removes that
item from the list:
>>> a = [11, 22, 33, 44, ]
>>> b = a.pop()
>>> a
[11, 22, 33]
>>> b Note that the append and pop methods taken
44 together can be used to implement
>>> b = a.pop() a stack, that is a LIFO (last in first out) data
structure.
>>> a
[11, 22]
>>> b
33

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Example
Fergusson College
• Concatenate two lists index-wise
– Write a program to add two lists index-wise. Create a new list that
contains the 0th index item from both the list, then the 1st index
item, and so on till the last element. any leftover items will get
added at the end of the new list.
• Given:
– list1 = ["M", "na", "i", “Rah"]Use the zip() function. This function takes two
or more iterables (like list, dict, string),
– list2 = ["y", "me", "s", “ul"] aggregates them in a tuple, and returns it.
list1 = ["M", "na", "i", “Rah"]
• Expected output: list2 = ["y", "me", "s", “ul"]
list3 = [i + j for i, j in
– ['My', 'name', 'is', ‘Rahul'] zip(list1,list2)]
print(list3)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Example
Fergusson College
• Write a program that returns a list that contains only the elements that are common
between the lists (without duplicates). Make sure your program works on two lists
of different sizes.

one = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


two = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
both=[]
if len(one) < len(two):
for i in one:
if i in two and i not in both:
OUTPUT
both.append(i)
if len(one) > len(two):
[1, 2, 3, 5, 8, 13]
for i in two:
if i in one and i not in both:
both.append(i)
print(both)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Example
Fergusson College
• Write a program that takes a list of numbers (for example, a = [5, 10,
15, 20, 25]) and makes a new list of only the first and last elements
of the given list.

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Examples
Fergusson College
• Replace each element in a list L with its square.
L = [5, 10, 15, 20, 25])
for i in range(len(L)):
L[i] = L[i]**2

• Given a list L that contains numbers between 1 and 100, create a new list whose
first element is how many ones are in L, whose second element is how many twos are
in L, etc.
frequencies = []
for i in range(1,101):
frequences.append(L.count(i))

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


UsingFergusson
Lists as stacks and Queues
College
• Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in
Python make the code short and simple.
• To add an item to the top of the list, i.e., to push an item, we use append() function
and to pop out an element we use pop() function.
• These functions work quiet efficiently and fast in end operations.
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal") Output:
print(stack) ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
# Removes the last item
print(stack.pop()) ['Amar', 'Akbar', 'Anthony', 'Ram']
print(stack) Ram
['Amar', 'Akbar', 'Anthony']
# Removes the last item
print(stack.pop())
print(stack)

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


UsingFergusson
Lists as stacks and Queues
College
• Queue works on the principle of “First-in, first-out”. Below is list implementation of
queue.
• We use pop(0) to remove the first item from a list.
queue = ["Amar", "Akbar", "Anthony"]
queue.append("Ram")
queue.append("Iqbal")
print(queue)
# Removes the first item Output:
print(queue.pop(0)) ['Amar', 'Akbar', 'Anthony', 'Ram',
print(queue) 'Iqbal']
# Removes the first item
Amar
['Akbar', 'Anthony', 'Ram', 'Iqbal']
print(queue.pop(0))
Akbar
print(queue)
['Anthony', 'Ram', 'Iqbal']

M.Sc.(CA) Dept. ACBCS College, Nashik -Rahul Sonawane


Fergusson College

Visit Us
http://www.aef.edu.in/acbcs

M.Sc.(CA) Dept. ACBCS College, NashikCenter For Business And Computer Studies,
Ashoka -Rahul Sonawane
Nashik

You might also like