Chapter 3: Structured Types, Mutability and Higher-Order Functions
Chapter 3: Structured Types, Mutability and Higher-Order Functions
Strings :
String represents a group of characters.
To create a string in python, assign a group of characters to a variable, should be
enclosed inside single quotes or double quotes:
Str1= ‗hello world‘
Str2= ―hello world‖
Also we can use triple single quotes or triple double quotes while creating the string
to represent a string that occupies several lines:
Str3= ‗‘‘hello
World‘‘‘
Str4= ―‖‖hello
World‖‖‖
To display substring inside string:
Str5= ‗I am ―python‖ program‘
Str6= ―I am ‗python‘ program‖
To print a string:
print Str1
Output: hello world
Length of String:
The length of the string represents the number of characters in a string. We use len()
function. This function gives the number of characters including spaces in the string
str='core python'
n=len(str)
print (n)
Output: 11
Indexing in String:
Index represents the position number. They are written using square braces [ ]. By
specifying the index we can refer individual elements.
Str[i] represents ith element of string. Positive index starts from left to right and
negative index starts from right to left (end of the string).
str='core python'
n=len(str)
i=0
while i<n: #access string using positive indexing
print(str[i], end=" ")
i+=1
print("\n---------------------------------------------------")
i=-1
while i>=-n: #access string using Negative indexing
print(str[i], end=" ")
i-=1
print("\n---------------------------------------------------")
Ouput:
core python
---------------------------------------------------
nohtyp eroc
---------------------------------------------------
core python
---------------------------------------------------
core python
---------------------------------------------------
nohtyp eroc
Slicing in String:
Slice represents a part or piece of a string.
Syntax: stringname [ start : stop : stepsize ]
str='core python'
print (str[0:9:1]) #accessing strting from 0th to 8th element in steps of 1
print (str[0:9:2]) #accessing strting from 0th to 8th element in steps of 2
print (str[::]) #access string from start to last charcter
print (str[2:4:1]) #accessing strting from str[2] to str[4] element in steps of 1
print (str[::2]) #accessing entire strting in steps of 2
print (str[::-1]) #reverse the string
Output:
core pyth
cr yh
core python
re
cr yhn
nohtyp eroc
Repeating in String:
str='core python'
print (str*2)
s=str[5:7]*3
print(s)
Output:
core pythoncore python
pypypy
Concatenation of String:
str1='core python'
str2="programs"
str3=str1+str2
print (str3)
Output:
core pythonprograms
Comparing Strings:
str1="Box"
str2="box"
if(str1==str2):
print ("both are same")
else:
print ("both are not same")
Output:
both are not same
n = main_str.find(sub_str,0,len(main_str))
if n == -1:
print "sub string is not found"
else:
print "sub string found at position:", n+1
Another Way:
main_str= raw_input('Enter the main string:')
sub_str= raw_input('Enter the sub string:')
flag=False
pos = -1
n=len(main_str)
while True:
pos = main_str.find(sub_str,pos+1,n)
if pos == -1:
break
print "Found at position:", pos+1
flag = True
if flag == False:
print "sub string is not found"
Syntax: stringname.replace(old,new)
str1="this is old string"
s1="old"
s2="new"
str2= str1.replace(s1,s2)
print str1
print str2
Split() of string:
The split() method is used to brake a string into pieces. These pieces are returned as a
list. In split() method the argument, separator that represents where to separate or cut
the string.
Syntax : stringname.split(separator)
str1= "One, Two, Three, Four"
str2= str1.split(',')
print str2
Output:
['One', ' Two', ' Three', ' Four']
join() of string:
When a group of strings are given, it is possible to join them all and make a single
string. For this join method is used:
Syntax: separator.join(str)
Where separator represents the character to be used between the strings in the output.
‗str‘ represents a tuple or list of strings.
str1=('one','two','three')
str2='-'.join(str1)
print str2
str1=['hello','world','this','is','python']
sep=" "
str2=sep.join(str1)
print str2
Output:
str1="pYthon pRograMming"
print str1.upper()
print str1.lower()
print str1.swapcase()
print str1.title()
str1="This is python"
print str1.startswith('This')
print str1.startswith('The')
print str1.endswith('python')
print str1.endswith('program')
Sorting of a string:
We can sort a group of strings into alphabetical order using sort() method and sorted()
function.
Syntax: str.sort(), str1=sorted(str)
str1=[]
n=int(raw_input('How many Strings?'))
for i in range(n):
print "Enter the string:"
str1.append(raw_input())
str2 = sorted(str1)
print "Ascending order sorted list:"
for i in str2:
print i
print '\n'
print "Descending order sorted list:"
str2 = sorted(str1, reverse=True) #for descending order
for i in str2:
print i
Basically String is also a structured type data types, but other than this we will learn 3
types: Tuples, list and dict.
Lists:
List is an ordered sequence of values, where each value is identified by an index.
In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
# empty list
my_list = []
print(my_list)
# list of integers
my_list = [1, 2, 3]
print(my_list)
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
print(my_list)
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)
Output:
[]
[1, 2, 3]
[1, 'Hello', 3.4]
['mouse', [8, 4, 6], ['a']]
List Index: We can use the index operator [] to access an item in a list. Index starts
from 0. So, a list having 5 elements will have index from 0 to 4.
my_list = ['l','j','i','e','t','s','g','h','y']
n_list = ["Happy", [2,0,1,5]]
odd = [2, 4, 6, 8]
print(my_list[0]) #indexing
print(my_list[2])
print(my_list[4])
print("negative indexing")
print(my_list[-1]) #negative indexing
print(my_list[-5])
print("nested indexing")
print(n_list[0][1]) #nested indexing
print(n_list[1][3])
print("slicing")
print(my_list[2:5]) #slicing
print(my_list[:-5])
print(my_list[5:])
print(my_list[:])
print("change element of list")
print(odd)
odd[0] = 1 #change element of list
print(odd)
odd[1:4] = [3, 5, 7]
print(odd)
print("append element to list")
odd.append(7) #append element
print(odd)
print("extend element to list")
odd.extend([9, 11, 13]) #extend element
print(odd)
print("+ operator to combine two lists")
print(odd + [9, 7, 5])
print("* operator repeats a list for the given number of times.")
print(["re"] * 3)
print("delete element of list")
del odd[2]
print(odd)
del odd[1:5]
print(odd)
del odd
print(odd)
Output:
l
i
t
negative indexing
y
t
nested indexing
a
5
slicing
['i', 'e', 't']
['l', 'j', 'i', 'e']
['s', 'g', 'h', 'y']
['l', 'j', 'i', 'e', 't', 's', 'g', 'h', 'y']
change element of list
[2, 4, 6, 8]
[1, 4, 6, 8]
[1, 3, 5, 7]
append element to list
[1, 3, 5, 7, 7]
extend element to list
[1, 3, 5, 7, 7, 9, 11, 13]
+ operator to combine two lists
[1, 3, 5, 7, 7, 9, 11, 13, 9, 7, 5]
* operator repeats a list for the given number of times.
['re', 're', 're']
delete element of list
[1, 3, 7, 7, 9, 11, 13]
[1, 11, 13]
Traceback (most recent call last):
File
"C:/Users/Shefa20393/AppData/Local/Programs/Python/Python36/test.py
", line 40, in <module>
print(odd)
NameError: name 'odd' is not defined
Creating list using range() : We can use the range() to generate a sequence of
integers which can be stored in a list.
lst=list(range(4,9,2))
print lst
Output:
[4, 6, 8]
Output:
True
False
True
Output:
I like apple
I like banana
I like mango
Updating elements of a list : Lists are mutable. It means we can modify the content
of a list. We can append, update or delete the elements of a list depending upon our
requirements.
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3]
Tuples:
Like strings, tuples are ordered sequences of elements. The difference is that the
elements of a tuple need not be characters. The individual elements can be of any
type, and need not be of the same type as each other.
In Python programming, a tuple is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned whereas in a list,
elements can be changed.
Advantages of Tuple over List:
Since, tuples are quite similiar to lists, both of them are used in similar situations as
well. However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
1. We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
2. Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
3. Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
4. If you have data that doesn't change, implementing it as tuple will guarantee
that it remains write-protected.
Literals of type tuple are written by enclosing a comma-separated list of elements
within parentheses.
For example,
t1=()
t2=(1, 'two', 3)
t3=(1,) #singletone element
print (t1)
print (t2)
print (t3)
Output:
()
(1, 'two', 3)
(1,)
Output:
((1, 'two', 3), 3.25)
(1, 'two', 3, (1, 'two', 3), 3.25)
(1, 'two', 3)
(3, (1, 'two', 3), 3.25)
student =(10,'Alpa',20,30,40)
rno, name = student[0:2]
print rno
print name
marks=student[2:5]
for i in marks:
print i
Output:
Output:
Nested tuple:
emp=((90,'Alpa',30000),(52,'kinjal',25000),(64,'Bijal',35000))
print emp
print emp[1][1]
print sorted(emp)
print sorted(emp,reverse=True)
print sorted(emp,key=lambda x:x[1]) #sort on name
print sorted(emp,key=lambda x:x[2]) #sort on salary
Output:
Output:
num=num1+num[pos:]
print num
Output:
Output:
Dictionary:
Objects of type dict (short for dictionary) are like lists except that ―indices‖ need not be
integers—they can be values of any immutable type. Since they are not ordered, we call
them keys rather than indices. Think of a dictionary as a set of key/value pairs. Literals of
type dict are enclosed in curly braces, and each element is written as a key followed by a
colon followed by a value.
Example:
monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,
'May':5,1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'}
print ('The third month is ' + monthNumbers[3])
dist = monthNumbers['Apr'] - monthNumbers['Jan']
print ('Apr and Jan are', dist, 'months apart')
Output:
The third month is Mar
Apr and Jan are 3 months apart
Example:
#Different type Dict creating
my_dict = {}
my_dict = {1: 'apple', 2: 'ball'}
my_dict = {'name': 'John', 1: [2, 4, 3]}
my_dict = dict({1:'apple', 2:'ball'})
my_dict = dict([(1,'apple'), (2,'ball')])
my_dict = {'name':'Jack', 'age': 26}
print("Displying Dictionary")
print(my_dict)
print(my_dict['name'])
print(my_dict.get('age'))
print("change element of Dictionary")
my_dict['age'] = 27
print(my_dict)
print("add element to Dictionary")
my_dict['address'] = 'Downtown'
print(my_dict)
print("delete element from Dictionary")
del my_dict['address']
print(my_dict)
print(my_dict.popitem())
print("fromkey method")
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
list(sorted(marks.keys()))
Output:
Displying Dictionary
{'name': 'Jack', 'age': 26}
Jack
26
change element of Dictionary
{'name': 'Jack', 'age': 27}
add element to Dictionary
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
delete element from Dictionary
{'name': 'Jack', 'age': 27}
('age', 27)
fromkey method
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
d.update(ud)
print d
O/P: {1: 'alpa', 2: 'kinjal', 3: 'shefa'}
{1:'alpa',2: 'kinjal',3: 'shefa',4: 'varsha'}
values() Return a new view of the d={1:'alpa',2:'kinjal',3:'varsha'}
dictionary's values print d.values()
O/P: ['alpa', 'kinjal', 'shefa']
squares1[x] = x*x
print(squares1)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Output:
True
False
False
Output:
1
9
25
49
81
Output:
[(10, 'red'), (15, 'blue'), (25, 'white'), (35, 'green')]
[(15, 'blue'), (35, 'green'), (10, 'red'), (25, 'white')]
[(35, 'green'), (25, 'white'), (15, 'blue'), (10, 'red')]
[(25, 'white'), (10, 'red'), (35, 'green'), (15, 'blue')]
Output:
{'GERMANY': 'BERLIN', 'INDIA': 'NEW DELHI', 'USA': 'WASHINGTON'}
Output:
{'Shefa': '30', 'Alpa': '10', 'Varsha': '20'}
Ordered Dictionary:
An ordered dictionary is a dictionary but it will keep the order of the elements. The
elements are stored and maintained in the same order as they were entered into the
ordered dictionary.
from collections import OrderedDict
d=OrderedDict()
d[10]='A'
d[11]='B'
d[12]='C'
Output:
10 A
11 B
12 C
Lists differ from tuples in one hugely important way: lists are mutable. In contrast,
tuples and strings are immutable. There are many operators that can be used to create
objects of these immutable types, and variables can be bound to objects of these types.
But objects of immutable types cannot be modified. On the other hand, objects of type
list can be modified after they are created.
Cloning:
Though allowed, it is usually prudent to avoid mutating a list over which one is
iterating.
def removeDups(L1, L2):
"""Assumes that L1 and L2 are lists.
Removes any element from L1 that also occurs in L2"""
for e1 in L1:
if e1 in L2:
L1.remove(e1)
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDups(L1, L2)
print ('L1 =', L1)
Output:
L1 = [2, 3, 4]
List Comprehension:
List comprehension provides a concise way to apply an operation to the values in a
sequence. It creates a new list in which each element is the result of applying a given
operation to a value from a sequence (e.g., the elements in another list).
L = [x**2 for x in range(1,7)]
print (L)
Output:
[1, 4, 9, 16, 25, 36]
The for clause in a list comprehension can be followed by one or more if and for
statements that are applied to the values produced by the for clause. These additional
clauses modify the sequence of values generated by the first for clause and produce a
new sequence of values, to which the operation associated with the comprehension is
applied.
mixed = [1, 2, 'a', 3, 4.0]
print ([x**2 for x in mixed if type(x) == int])
Output:
[1, 4, 9]
Function as objects :
In Python, functions are first-class objects. That means that they can be treated like
objects of any other type, e.g., int or list. They have types, e.g., the expression type(fact)
has the value <type 'function'>; they can appear in expressions, e.g., as the right-hand side
of an assignment statement or as an argument to a function; they can be elements of lists;
etc.
Using functions as arguments can be particularly convenient in conjunction with lists. It
allows a style of coding called higher-order programming.
def factI(n):
"""Assumes that n is an int > 0
Returns n!"""
result = 1
while n > 1:
result = result * n
n -= 1
return result
def factR(n):
"""Assumes that n is an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*factR(n - 1)
def fib(n):
"""Assumes n an int >= 0
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def testFib(n):
for i in range(n+1):
print 'fib of', i, '=', fib(i)
Output:
L = [1, -2, 3.33]
Apply abs to each element of L.
L = [1, 2, 3.33]
Apply int to each element of [1, 2, 3.33]
L = [1, 2, 3]
Apply factorial to each element of [1, 2, 3]
L = [1, 2, 6]
Apply Fibonnaci to each element of [1, 2, 6]
L = [1, 2, 13]
Python has a built-in higher-order function, map, that is similar to, but more general
than, the applyToEach function defined.
In its simplest form the first argument to map is a unary function (i.e., a function that
has only one parameter) and the second argument is any ordered collection of values
suitable as arguments to the first argument.
It returns a list generated by applying the first argument to each element of the second
argument.
For example, the expression map(fact, [1, 2, 3]) has the value [1, 2, 6]. More
generally, the first argument to map can be of function of n arguments, in which case
it must be followed by n subsequent ordered collections.
L1 = [100, -28, 36]
L2 = [2, 57, 9]
print map(abs,L1)
print map(min, L1, L2)
Output:
[100, 28, 36]
[2, -28, 9]
The first argument func is the name of a function and the second a sequence (e.g. a
list) seq. map() applies the function func to all the elements of the sequence seq. It
returns a new list with the elements changed by func.
Example-1 Of map():
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = map(fahrenheit, temp)
C = map(celsius, F)
Output:
>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>> C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit)
>>> print C
[39.200000000000003, 36.5, 37.300000000000004, 37.799999999999997]
The function filter(f,l) needs a function f as its first argument. f returns a Boolean
value, i.e. either True or False. This function will be applied to every element of the
list l. Only if f returns True will the element of the list be included in the result list.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:
At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on
which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]
In the next step func will be applied on the previous result and the third element of the
list, i.e. func(func(s1, s2),s3)
The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]
Continue like this until just one element is left and return this element as the result of
reduce()
Examples of reduce():
1) Determining the maximum of a list of numerical values by using reduce:
Method Description
abs() returns absolute value of a number
all() returns true when all elements in iterable is true
any() Checks if any Element of an Iterable is True
ascii() Returns String Containing Printable Representation
bin() converts integer to binary string
bool() Coverts a Value to Boolean
bytearray() returns array of given byte size
bytes() returns immutable bytes object
callable() Checks if the Object is Callable
chr() Returns a Character (a string) from an Integer
classmethod() returns class method for given function
compile() Returns a Python code object
complex() Creates a Complex Number
delattr() Deletes Attribute From the Object
dict() Creates a Dictionary
dir() Tries to Return Attributes of Object
divmod() Returns a Tuple of Quotient and Remainder
enumerate() Returns an Enumerate Object
eval() Runs Python Code Within Program
exec() Executes Dynamically Created Program
filter() constructs iterator from elements which are true
float() returns floating point number from number, string
format() returns formatted representation of a value
frozenset() returns immutable frozenset object
getattr() returns value of named attribute of an object
globals() returns dictionary of current global symbol table
hasattr() returns whether object has named attribute
hash() returns hash value of an object
Method Description
help() Invokes the built-in Help System
hex() Converts to Integer to Hexadecimal
id() Returns Identify of an Object
input() reads and returns a line of string
int() returns integer from a number or string
isinstance() Checks if a Object is an Instance of Class
issubclass() Checks if a Object is Subclass of a Class
iter() returns iterator for an object
len() Returns Length of an Object
list() Function creates list in Python
locals() returns dictionary of current local symbol table
map() Applies Function and Returns a List
max() returns largest element
memoryview() returns memory view of an argument
min() returns smallest element
next() Retrieves Next Element from Iterator
object() Creates a Featureless Object
oct() converts integer to octal
open() Returns a File object
ord() returns Unicode code point for Unicode character
pow() returns x to the power of y
print() Prints the Given Object
property() returns a property attribute
range() return sequence of integers between start and stop
repr() returns printable representation of an object
reversed() returns reversed iterator of a sequence
round() rounds a floating point number to ndigits places.
set() returns a Python set
setattr() sets value of an attribute of object
slice() creates a slice object specified by range()
sorted() returns sorted list from a given iterable
staticmethod() creates static method from a function
str() returns informal representation of an object
sum() Add items of an Iterable
Method Description
super() Allow you to Refer Parent Class by super
tuple() Function Creates a Tuple
type() Returns Type of an Object
vars() Returns __dict__ attribute of a class
zip() Returns an Iterator of Tuples
__import__() Advanced Function Called by import
Q: Write a program to open the file test.txt and read it line by line. For each line, split
the line into a list of words using the split function. For each word, check to see if the
word is already in a list. If the word is not in the list, add it to the list. When the
program completes, sort and print the resulting words in alphabetical order.
File: test.txt
hello this is an apple
apple is fruit
File:FileWordListSort.py
# File words list and sort it
fname = ' test.txt'
wordlist = []
with open(fname, 'r') as f:
for line in f:
words = line.split()
for word in words:
if word not in wordlist:
wordlist.append(word)
Output:
Q: Write a program that reads the words in words.txt and stores them as keys in a
dictionary and count the frequency of it as a value and print 10 records with highest.
File: wordcount.py
#wordcount program
fr = open("1.txt")
wc = {}
wl=[]
for line in fr:
words = line.split()
for word in words:
word=word.lower()
if word not in wc:
wc[word] = 1
else:
wc[word] += 1
wl.sort(reverse=True)
#print wl
#print "Sort dic : ",wc
i = 0
for key in wc:
i+=1
print key, " - ", wc[key]
if i==10:
break
Output:
Output:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Output:
Slice of String : his
Slice of String : Ti sPho