Python Module 2
Python Module 2
DEPARTMENT OF ECE
NOTES
PYTHON PROGRAMMING
1BPLC105B/205B
PYTHON PROGRAMMING
Module-2
Python Programming Dept. ECE
Module – 2
Strings
The indexing operator (Python uses square brackets to enclose the index) selects a single
character substring from a string:
5.1.4 Length
The len function, when applied to a string, returns the number of characters in a string:
>>> word = "banana"
>>> len(word)
6
>>>size = len(word)
>>>last = word[size]
That won’t work. It causes the runtime error IndexError: string index out of range. The reason
is that there is no character at index position 6 in "banana". Because we start counting at zero,
the six indexes are numbered 0 to 5. To get the last character, we have to subtract 1 from the
length of word:
size = len(word)
last = word[size-1]
Alternatively, we can use negative indices, which count backward from the end of the string.
>>>greet="Hello World"
>>>print(greet[-1])
d
Python Programming Dept. ECE
The following example shows how to use concatenation and a for loop to generate an
abecedarian series. Abecedarian refers to a series or list in which the elements appear in
alphabetical order. For example, in Robert McCloskey’s book Make Way for Ducklings, the
names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This
loop outputs these names in order:
prefixes = "JKLMNOPQ"
suffix = "ack"
for p in prefixes:
print(p + suffix)
5.1.6 Slices
A substring of a string is obtained by taking a slice. Similarly, we can slice a list to refer to
some sub list of the items in the list:
>>> phrase = "Pirates of the Caribbean"
>>> print(phrase[0:7])
Python Programming Dept. ECE
Pirates
>>> print(phrase[11:14])
the
>>> print(phrase[13:24])
e Caribbean
>>> friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
>>> print(friends[2:4])
['Brad', 'Angelina']
The operator [n:m] returns the part of the string from the n’th character to the m’th character,
including the first but excluding the last. This behavior makes sense if you imagine the
indices pointing between the characters, as in the following diagram:
Three tricks are added to this: if you omit the first index (before the colon), the slice starts at
the beginning of the string (or list). If you omit the second index, the slice extends to the end
of the string (or list). Similarly, if you provide value for n that is bigger than the length of the
string (or list), the slice will take all the values up to the end. (It won’t give an “out of range”
error like the normal indexing operation does.) Thus:
>>> word = "banana"
>>> word[:3]
'ban'
>>> word[3:]
'ana'
>>> word[3:999]
'ana'
5.1.7 String comparison
The comparison operators work on strings. To see if two strings are equal:
word = "banana"
if word == "banana":
print("Yes, we have no bananas!")
Python Programming Dept. ECE
Instead of producing the output Jello, world!, this code produces the runtime error
TypeError: 'str' object does not support item assignment.
The best you can do is create a new string that is a variation on the original:
greeting = "Hello, world!"
new_greeting = "J" + greeting[1:]
print(new_greeting)
The in operator tests for membership. When both of the arguments to in are
strings, in checks whether the left argument is a substring of the right argument.
>>>"pa"in"apple"
False
Note that a string is a substring of itself, and the empty string is a substring of
any other string.
>>>"a"in "a"
True
>>>"apple"in "apple"
True
>>>""in "a"
True
>>>""in "apple"
True
def remove_vowels(phrase):
vowels = "aeiou"
string_sans_vowels = ""
for letter in phrase:
if [Link]() not in vowels:
string_sans_vowels += letter
return string_sans_vowels
remove_vowels("hello")
haystack="Bananarama!"
print([Link]('a'))
print(my_find(haystack,'a'))
In a sense, find is the opposite of the indexing operator. Instead of taking an index
and extracting the corresponding character, it takes a character and finds the index
where that character appears. If the character is not found, the function returns-1.
This is another example where we see a return statement inside a loop.
If letter == needle, the function returns immediately, breaking out of the loop
prematurely. If the character doesn’t appear in the string, then the program exits
the loop normally and returns-1.
This pattern of computation is sometimes called a eureka traversal or short-circuit
evaluation, because as soon as we find what we are looking for, we can cry
“Eureka!”, take the short-circuit, and stop looking.
The following program counts the number of times the letter a appears in a string,
and is another example of the counter pattern introduced in Counting digits:
def count_a(text):
count = 0
for letter in text:
if letter == "a":
count += 1
return count
print(count_a("banana") == 3)
Example 1
def find2(haystack, needle, start):
for index,letter in enumerate(haystack[start:]):
if letter == needle:
return index + start
return-1
print(find2("banana", "a", 2) == 3)
Example 2
def find(haystack, needle, start=0):
for index,letter in enumerate(haystack[start:]):
if letter == needle:
return index + start
return-1
Example 3
def find(haystack, needle, start=0, end=-1):
for index,letter in enumerate(haystack[start:end])
if letter == needle:
return index + start
return-1
One of the most useful methods on strings is the split method: it splits a single
multi-word string into a list of individual words, removing all the whitespace
between them. (Whitespace means any tabs, newlines, or spaces.) This allows us
to read input as a single string, and split it into words.
We’ll show just one example of how to strip punctuation from a string. Remember
that strings are immutable, so we cannot change the string with the punctuation
— we need to traverse the original string and create a new string, omitting any
punctuation:
Example
punctuation="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
def remove_punctuation(phrase):
phrase_sans_punct = ""
for letter in phrase:
if letter not in punctuation:
phrase_sans_punct + = letter
return phrase_sans_punct
import string
def remove_punctuation(phrase):
phrase_sans_punct = ""
for letter in phrase:
if letter not in [Link]:
phrase_sans_punct += letter
return phrase_sans_punct
my_story = """
Pythons are constrictors, which means that they will 'squeeze' the life out of their
prey. They coil themselves around their prey and with each breath the creature
takes the snake will squeeze a little tighter until they stop breathing completely.
Once the heart stops the prey is swallowed whole. The entire animal is digested
in the snake's stomach except for fur or feathers. What do you think happens to
the fur, feathers, beaks, and eggshells? The 'extra stuff' gets passed out as —
you guessed it — snake POOP!
"""
Python Programming Dept. ECE
words = remove_punctuation(my_story).split()
print(words)
The easiest and most powerful way to format a string in Python 3 is to use the
format() method. To see how this works, let’s start with a few examples.
Output
His name is Arthur!
I am Alice and I am 10 years old.
I am 10 and I am Alice years old.
2**10 = 1024 and 4 * 5 = 20.000000
The template string contains place holders, ... {0} ... {1} ... {2} ...etc. The format
method substi tutes its arguments into the place holders. The numbers in the place
holders are indexes that determine which argument gets substituted — make sure
you understand line 6 above!
But there’s more! Each of the replacement fields can also contain a format
specification — it is always introduced by the : symbol (Line 13 above uses one.)
This modifies how the substitutions are made into the template, and can
control things like:
Python Programming Dept. ECE
• whether the field is aligned to the left <, center ^, or right >
• the width allocated to the field within the result string (a number like 10)
• the type of conversion (we’ll initially only force conversion to float, f, as we
did in line 13 of the code above,
or perhaps we’ll ask integer numbers to be converted to hexadecimal using x)
• if the type conversion is a float, you can also specify how many decimal places
are wanted (typically, .2f is useful for working with currencies to two decimal
places.)
name1 = "Paris"
name2 = "Whitney"
name3 = "Hilton"
print("|||{0:<15}|||{1:^15}|||{2:>15}|||Born in {3}|||"
.format(name1, name2, name3, 1981))
OUTPUT
Example
letter = """
Dear {0} {2},
{0}, I have an interesting money-making proposition for you!
If you deposit $10 million into my bank account, I can
Python Programming Dept. ECE
OUTPUT
Dear ParisHilton.
Paris,I have an interesting money-making proposition for you!
If you deposit $10 million into my bank account, I can
double your money...
Dear Bill Gates.
Bill, I have an interesting money-making proposition for you!
If you deposit $10 million into my bank account I can
double your money...
As you might expect, you’ll get an index error if your placeholders refer to
arguments that you do not provide:
>>>"hello {3}".format("Dave")
Traceback(most recent call last):
File"<interactive input>",line1, in <module>
IndexError: tuple index out of range
Example
layout = "{0:>4}{1:>6}{2:>6}{3:>8}{4:>13}{5:>24}"
print([Link]("i", "i**2", "i**3", "i**5", "i**10", "i**20"))
for i in range(1, 11):
print([Link](i, i**2, i**3, i**5, i**10, i**20))
Python Programming Dept. ECE
5.2 Tuples
5.2.1 Tuples are used for grouping data
>>> julia[2]
1967
Tuples are immutable. Once Python has created a tuple in memory, it cannot be
changed.
Of course, even if we can’t modify the elements of a tuple, we can always make
the julia variable reference a new tuple holding different information.
>>> julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:] >>> julia ("Julia",
"Roberts", 1967, "Eat Pray Love", 2010, "Actress", "Atlanta, Georgia")
To create a tuple with a single element (but you’re probably not likely to do that
too often), we have to include the final comma, because without the final comma,
Python treats the (5) below as an integer in parentheses:
>>> tup = (5,)
Python Programming Dept. ECE
>>> type(tup)
<class 'tuple'>
>>> x = (5)
>>> type(x)
<class 'int'>
Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
right of the assignment.
One way to think of tuple assignment is as tuple packing/unpacking.
In tuple packing, the values on the left are ‘packed’ together in a tuple:
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
>>> bob = ("Bob", 19, "CS")
>>> (name, age, studies) = bob # tuple unpacking
>>> name
'Bob'
>>> age
19
>>> studies
'CS'
For example, to swap a and b:
temp = a
a=b
b = temp
Tuple assignment solves this problem neatly:
1
(a, b) = (b, a)
Python Programming Dept. ECE
The left side is a tuple of variables; the right side is a tuple of values. Each value
is assigned to its respective variable.
Naturally, the number of variables on the left and the number of values on the
right have to be the same:
def circle_stats(r):
""" Return (circumference, area) of a circle of radius r """
circumference = 2 * [Link] * r
area = [Link] * r * r
return (circumference, area)
5.3 Lists
A list is an ordered collection of values. The values that make up a list are called
its elements, or its items. We will use the term element or item to mean the same
thing.
Lists are similar to strings, which are ordered collections of characters, except
that the elements of a list can be of any type. Lists and strings — and other
collections that maintain the order of their items — are called sequences.
The index operator: []. The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> numbers[0]
17
If you try to access or assign to an element that does not exist, you get a runtime
error:
>>> numbers[2]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
IndexError: list index out of range
Each time through the loop, the variable i is used as an index into the list, printing
the i’th element. This pattern of computation is called a list traversal.
The function len returns the length of a list, which is equal to the number of its
elements. If you are going to use an integer index to access the list, it is a good
idea to use this value as the upper bound of a loop instead of a constant.
in and not in are Boolean operators that test membership in a sequence. We used
them previously with strings, but they also work with lists and other sequences:
counter = 0
for name, subjects in students:
if "CompSci" in subjects:
counter += 1
print("The number of students taking CompSci is", counter)
>>>first_list=[1,2,3]
>>>second_list=[4,5,6]
>>>both_lists=first_list+second_list
>>>both_lists
[1,2,3,4,5,6]
Python Programming Dept. ECE
>>>[0] * 4
[0,0,0,0]
>>>[1,2,3] * 3
[1,2,3,1,2,3,1,2,3]
A slice is a way to extract a portion of a list (or any sequence) using the colon :
>>>a_list=["a","b","c","d","e","f"]
>>>a_list[1:3]
['b','c']
>>>a_list[:4]
['a','b','c','d']
>>>a_list[3:]
['d','e','f']
>>>a_list[:]
['a','b','c','d','e','f']
Lists are mutable, which means we can change their elements. Using the index
operator on the left side of an assignment, we can update one of the elements.
>>>fruit=["banana","apple","quince"]
>>>fruit[0]="pear"
>>>fruit[2]="orange"
>>>fruit
['pear','apple','orange']
>>>my_list=["T","E","S","T"]
>>>my_list[2]="X"
>>>my_list
['T','E','X','T']
>>>a_list
['a','x','y','d','e','f']
We can also remove elements from a list by assigning an empty list to them:
>>>a_list=["a","b","c","d","e","f"]
>>>a_list[1:3]=[]
>>>a_list
['a','d','e','f']
And we can add elements to a list by squeezing them into an empty slice at the
desired location:
>>>a_list=["a","d","f"]
>>>a_list[1:1]=["b","c"]
>>>a_list
['a','b','c','d','f']
>>>a_list[4:4]=["e"]
>>>a_list
['a','b','c','d','e','f']
>>>a=["one","two","three"]
>>>del a[1]
>>>a
['one','three']
As you might expect, del causes a runtime error if the index is out of range. You
can also use del with a slice to delete a sublist.
a = "banana"
b = "banana"
we know that a and b will refer to a string object with the letters "banana". But
we don’t know yet whether they point to the same string object. There are two
possible ways the Python interpreter could arrange its memory:
In one case, a and b refer to two different objects that have the same value. In
the second case, they refer to the same object.
We can test whether two names refer to the same object using the is operator:
>>> a is b
True
This tells us that both a and b refer to the same object, and that it is the second of
the two state snapshots that accurately describes the relationship.
Since strings are immutable, Python optimizes resources by making two names
that refer to the same string value refer to the same object.
a and b have the same value but do not refer to the same object.
Python Programming Dept. ECE
5.3.10 Aliasing
>>> a = [1, 2, 3]
>>> b = a
>>> a is b
True
Because the same list has two different names, a and b, we say that it is aliased.
Changes made with one alias affect the other:
>>> b[0] = 5
>>> a
[5, 2, 3]
If we want to modify a list and also keep a copy of the original, we need to be
able to make a copy of the list itself, not just the reference. This process is
sometimes called cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator:
>>> a = [1, 2, 3]
>>> b = a[:]
>>> b
[1, 2, 3]
Taking any slice of a creates a new list. In this case the slice happens to consist
of the whole list. So now the relationship is like this:
Python Programming Dept. ECE
Now we are free to make changes to b without worrying that we’ll inadvertently
be changing a:
>>> b[0] = 5
>>> a
[1, 2, 3]
The for loop also works with lists, as we’ve already seen.
The generalized syntax of a for loop is:
for <VARIABLE> in <LIST>:
<BODY>
Example
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
for friend in friends:
print(friend)
Example
for number in range(20):
if number % 3 == 0:
print(number)
for fruit in ["banana", "apple", "quince"]:
print("I like to eat " + fruit + "s!")
Since lists are mutable, we often want to traverse a list, changing each of its
elements. The following squares all the numbers in the list xs:
xs = [1, 2, 3, 4, 5]
for i in range(len(xs)):
xs[i] = xs[i]**2
enumerate generates pairs of both (index, value) during the list traversal. Try this
next example to see more clearly how enumerate works:
Example
xs = [1, 2, 3, 4, 5]
Python Programming Dept. ECE
Example
for (i, v) in enumerate(["banana", "apple", "pear", "lemon"]):
print(i, v)
OUTPUT
0 banana
1 apple
2 pear
3 lemon
Passing a list as an argument actually passes a reference to the list, not a copy or
clone of the list. So parameter passing creates an alias for you: the caller has one
variable referencing the list, and the called function has an alias, but there is
only one underlying list object.
def double_stuff(stuff_list):
""" Overwrite each element in a_list with double its value. """
for (index, stuff) in enumerate(stuff_list):
stuff_list[index] = 2 * stuff
things = [2, 5, 9]
double_stuff(things)
print(things)
OUTPUT
[4, 10, 18]
5.3.14 List methods
The dot operator can also be used to access built-in methods of list objects.
We’ll start with the most useful method for adding something onto the end of an
existing list:
Python Programming Dept. ECE
append is a list method which adds the argument passed to it to the end of the
list. We’ll use it heavily when we’re creating new lists.
>>> mylist = []
>>> [Link](5)
>>> [Link](27)
>>> [Link](3)
>>> [Link](12)
>>> mylist
[5, 27, 3, 12]
>>>mylist
[5,12,27,3,12,5,9,5,11])
>>>[Link](9) # Find index of first 9 in mylist
6
>>>[Link]()
>>>mylist
[11,5,9,5,12,3,27,12,5]
>>>[Link]()
>>>mylist
[3,5,5,5,9,11,12,12,27]
>>>[Link](12) # Remove the first 12 in the list
>>>mylist
[3,5,5,5,9,11,12,27]
Python Programming Dept. ECE
Functions which take lists as arguments and change them during execution are
called modifiers, and the changes they make are called side effects.
A pure function does not produce side effects. It communicates with the calling
program only through parameters, which it does not modify, and a return value.
Here is double_stuff written as a pure function:
def double_stuff(a_list):
"""Return a new list which contains
doubles of the elements in a_list.
"""
new_list = []
for value in a_list:
new_elem = 2 * value
new_list.append(new_elem)
return new_list
>>>things=[2,5,9]
>>>more_things=double_stuff(things)
>>>things
[2,5,9]
>>>more_things
[4,10,18]
The pure version of double_stuff above makes use of an important pattern for
your toolbox. Whenever you need to write a function that creates and returns a
list, the pattern is usually:
Python Programming Dept. ECE
def primes_lessthan(n):
"""Return a list of all prime numbers less than n."""
result=[]
for i inrange(2,n):
if is_prime(i):
[Link](i)
return result
Two of the most useful methods on strings involve conversion to and from lists
of substrings. The split method (which we’ve already seen) breaks a string into a
list of words. By default, any number of whitespace characters is considered a
word boundary.
>>> [Link]("ai")
['The r', 'n in Sp', 'n...']
Python Programming Dept. ECE
The inverse of the split method is join. You choose a desired separator string
(often called the glue) and join the list with the glue between each of the elements.
>>>glue=";"
>>>phrase=[Link](words)
>>>phrase
'The;rain;in;Spain...'
The list that you glue together (words in this example) is not modified. Also, as
the next examples show, you can use empty glue or multi-character strings as
glue.
>>>"---".join(words)
'The---rain---in---Spain...'
>>>"".join(words)
'TheraininSpain...'
import random
joe = [Link]()
def sum1():
"""Build a list of random numbers, then sum them"""
xs = []
for i in range(10000000):
num = [Link](1000) # Generate one random number
[Link](num) # Save it in our list
tot = sum(xs)
return tot
def sum2():
"""Sum the random numbers as we generate them"""
tot = 0
for i in range(10000000):
num = [Link](1000)
tot += num
return tot
print(sum1())
print(sum2())
A nested list is a list that appears as an element in another list. In this list, the
element with index 3 is a nested list:
To extract an element from the nested list, we can proceed in two steps:
>>> elem = nested[3]
>>> elem[0]
10
>>> nested[3][1]
20
Bracket operators evaluate from left to right, so this expression gets the 3’th
element of nested and extracts the 1’th element from it.
5.3.21 Matrices