KVG College of Engineering
DEPARTMENT OF ECE
NOTES
PYTHON PROGRAMMING
1BPLC105B/205B
PYTHON PROGRAMMING
Module-2
Python Programming Dept. ECE
Module – 2
Strings
5.1.1 A compound data type
A string is a sequence of characters used to represent text. It is one of the fundamental data types in
Python. Types that comprise smaller pieces are called compound data types.
5.1.2 Working with strings as single things
>>> our_string = "Hello, World!"
>>> all_caps = our_string.upper()
>>> all_caps
'HELLO, WORLD!'
upper is a method that can be invoked on any string object to create a new string, in which
all the characters are in uppercase. (The original string our_string remains unchanged.) There
are also methods such as lower, capitalize, and swapcase.
Example
old = "hello, world!"
new = [Link]()
print(old)
print(new)
5.1.3 Working with the parts of a string
The indexing operator (Python uses square brackets to enclose the index) selects a single
character substring from a string:
>>> fruit = "banana"
>>> letter = fruit[1]
>>> print(letter)
a
The expression fruit[1] selects character number 1 from fruit, and creates a new string
containing just this one character. The variable letter refers to the result. When we display
letter
Computer scientists always start counting from zero! The letter at subscript position zero of
"banana" is b. So at position [1] we have the letter a. If we want to access the zero-eth letter
of a string, we just place 0, or any expression that evaluates to 0, in between the brackets:
Python Programming Dept. ECE
>>> letter = fruit[0]
>>> print(letter)
b
The expression in brackets is called an index. An index specifies a member of an ordered
collection, in this case the collection of characters in the string. The index indicates which
one you want, hence the name. It can be any integer expression.
We can use enumerate to visualize the indices:
>>> fruit = "banana"
>>> list(enumerate(fruit))
[(0, 'b'), (1, 'a'), (2, 'n'), (3, 'a'), (4, 'n'), (5, 'a')]
>>> friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
>>> friends[3]
'Angelina'
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
5.1.5 Traversal and the for loop
A lot of computations involve processing a string one character at a time. Often, they start at
the beginning, select each character in turn, do something to it, and continue until the end.
This pattern of processing is called a traversal.
Example 1
i=0
while i < len(fruit):
letter = fruit[i]
print(letter)
i+= 1
Example 2
word="Banana"
for letter in word:
print(letter)
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
Comparison operations are useful for putting words in lexicographical order:
word = "Zebra"
if word < "banana":
print("Your word, " + word + ", comes before banana.")
elif word > "banana":
print("Your word, " + word + ", comes after banana.")
else:
print("Yes, we have no bananas!")
5.1.8 Strings are immutable
Strings are immutable, which means you can’t change an existing string.
greeting = "Hello, world!"
greeting[0] = 'J'
print(greeting)
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)
5.1.9 The in and not in operators
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.
>>> "p" in "apple"
True
>>> "i" in "apple"
False
>>>"ap"in"apple"
True
Python Programming Dept. ECE
>>>"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
The not in operator returns the logical opposite results of in:
>>>"x" not in "apple"
True
Combining the in operator with string concatenation using +, we can write a
function that removes all the vowels from a string:
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")
5.1.10 A find function
def my_find(haystack, needle):
"""
Find and return the index of needle in haystack.
Return -1 if needle does not occur in haystack.
"""
Python Programming Dept. ECE
for index, letter in enumerate(haystack):
if letter == needle:
return index
return -1
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.
5.1.11 Looping and counting
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)
5.1.12 Optional parameters
To find the locations of the second or third occurrence of a character in a string,
we can modify the find function, adding a third parameter for the starting position
in the search string:
Python Programming Dept. ECE
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
5.1.13 The built-in find method
Returns the index of the first occurrence of a substring, or -1 if it is not found.
>>> "banana".find("nan")
2
>>> "banana".find("na", 3)
4
5.1.14 The split method
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.
>>> phrase = "Well I never did said Alice"
>>> words = [Link]()
>>> words
Python Programming Dept. ECE
['Well', 'I', 'never', 'did', 'said', 'Alice']
5.1.15 Cleaning up your strings
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
Fortunately, the Python string module already does it for us.
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 output: ['Pythons','are','constrictors',...,'it','snake','POOP']
5.1.16 The string format method
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.
phrase ="His name is{0}!".format("Arthur")
print(phrase)
name="Alice"
age = 10
phrase = "I am {1} and I am {0} years old.".format(age, name)
print(phrase)
phrase = "I am {0} and I am {1} years old.".format(age, name)
print(phrase)
x=4
y=5
phrase = "2**10 = {0} and {1} * {2} = {3:f}".format(2**10, x, y, x * y)
print(phrase)
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("Pi to three decimal places is {0:.3f}".format(3.1415926))
print("123456789 123456789 123456789 123456789 123456789 123456789")
print("|||{0:<15}|||{1:^15}|||{2:>15}|||Born in {3}|||"
.format(name1, name2, name3, 1981))
print("The decimal value {0} converts to hex value {0:x}".format(123456))
OUTPUT
Pi to three decimal places is 3.142
123456789 123456789 123456789 123456789 123456789 123456789
|||Paris||| Whitney|||Hilton|||Born in 1981|||
The decimal value 123456 converts to hex value 1e240
You can have multiple placeholders indexing the same argument, or perhaps even
have extra arguments that are not referenced at all:
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
double your money...
"""
print([Link]("Paris", "Whitney", "Hilton"))
print([Link]("Bill", "Henry", "Gates"))
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
>>> year_born = ("Paris Hilton", 1981)
This is an example of a data structure — a mechanism for grouping and
organizing data to make it easier to use. The pair is an example of a tuple.
Generalizing this, a tuple can be used to group any number of items into a single
compound value. Syntactically, a tuple is a comma-separated sequence of values.
Although it is not necessary, it is conventional to enclose tuples in parentheses:
>>> julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta,
Georgia")
The index operator selects an element from a tuple.
>>> julia[2]
1967
Tuples are immutable. Once Python has created a tuple in memory, it cannot be
changed.
>>> julia[0] = "X"
TypeError: 'tuple' object does not support item assignment
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'>
5.2.2 Tuple assignment
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:
>>> bob = ("Bob", 19, "CS") # tuple packing
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:
>>> (one, two, three, four) = (1, 2, 3)
ValueError: need more than 3 values to unpack
5.2.3 Tuples as return values
Functions can always only return a single value, but by making that value a tuple,
we can effectively group together as many values as we like, and return them
together. This is very useful — we often want to know some batsman’s highest
and lowest score, or we want to find the mean and the standard deviation, or we
want to know the year, the month, and the day, or if we’re doing some some
ecological modelling we may want to know the number of rabbits and the number
of wolves on an island at a given time.
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.2.4 Composability of Data Structures
students = [ ("John", ["CompSci", "Physics"]), ("Vusi", ["Maths", "CompSci",
"Stats"]), ("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]), ("Zuki",
["Sociology", "Economics", "Law", "Stats", "Music"])]
julia_more_info = ( ("Julia", "Roberts"), (8, "October", 1967), "Actress",
("Atlanta", "Georgia"), [ ("Duplicity", 2009), ("Notting Hill", 1999), ("Pretty
Woman", 1990), ("Erin Brockovich", 2000), ("Eat Pray Love", 2010), ("Mona
Lisa Smile", 2003), ("Oceans Twelve", 2004) ])
This property is known as being heterogeneous, meaning that it can be composed
of elements of different types.
Python Programming Dept. ECE
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.
5.3.1 List values
There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
numbers = [10, 20, 30, 40]
words = ["spam", "bungee", "swallow"]
A list within another list is said to be nested.
Finally, a list with no elements is called an empty list, and is denoted [].
stuffs = ["hello", 2.0, 5, [10, 20]]
>>> vocabulary = ["apple", "cheese", "dog"]
>>> numbers = [17, 123]
>>> an_empty_list = []
>>> print(vocabulary, numbers, an_empty_list)
["apple", "cheese", "dog"] [17, 123] []
5.3.2 Accessing elements
The index operator: []. The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> numbers[0]
17
Any expression evaluating to an integer can be used as an index:
>>> numbers[9-8]
123
>>> numbers[1.0]
Traceback (most recent call last):
Python Programming Dept. ECE
File "<interactive input>", line 1, in <module>
TypeError: list indices must be integers, not float
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
It is common (but wrong!) to use a loop variable as a list index.
horsemen = ["war", "famine", "pestilence", "death"]
for i in [0, 1, 2, 3]:
print(horsemen[i])
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.
horsemen = ["war", "famine", "pestilence", "death"]
for h in horsemen:
print(h)
5.3.3 List length
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.
horsemen = ["war", "famine", "pestilence", "death"]
for i in range(len(horsemen)):
print(horsemen[i])
horsemen = ["war", "famine", "pestilence", "death"]
for horseman in horsemen:
print horseman
Although a list can contain another list, the nested list still counts as a single
element in its parent list. The length of this list is 4:
Python Programming Dept. ECE
>>> len(["car makers", 1, ["Ford", "Toyota", "BMW"], [1, 2, 3]])
4
5.3.4 List membership
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:
>>> horsemen = ["war", "famine", "pestilence", "death"]
>>> "pestilence" in horsemen
True
>>> "debauchery" in horsemen
False
>>> "debauchery" not in horsemen
True
Nested Loops for Nested Data:
students = [ ("John", ["CompSci", "Physics"]), ("Vusi", ["Maths", "CompSci",
"Stats"]), ("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]), ("Zuki",
["Sociology", "Economics", "Law", "Stats", "Music"])]
#Count how many students are taking CompSci
counter = 0
for name, subjects in students:
if "CompSci" in subjects:
counter += 1
print("The number of students taking CompSci is", counter)
5.3.5 List operations
The + operator concatenates lists:
>>>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
Similarly, the * operator repeats a list a given number of times:
>>>[0] * 4
[0,0,0,0]
>>>[1,2,3] * 3
[1,2,3,1,2,3,1,2,3]
5.3.6 List slices
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']
5.3.7 Lists are mutable
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']
With the slice operator we can update a whole sublist at once:
>>>a_list=["a","b","c","d","e","f"]
>>>a_list[1:3]=["x","y"]
Python Programming Dept. ECE
>>>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']
5.3.8 List deletion
Using slices to delete list elements can be error-prone. Python provides an
alternative that is more readable. The del statement removes an element from a
list.
>>>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_list = ["a", "b", "c", "d", "e", "f"]
>>> del a_list[1:5]
>>> a_list
['a', 'f']
5.3.9 Objects and references
Python Programming Dept. ECE
After we execute these assignment statements
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.
This is not the case with lists:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> a is b
False
a and b have the same value but do not refer to the same object.
Python Programming Dept. ECE
5.3.10 Aliasing
Since variables refer to objects, if we assign one variable to another, both
variables refer to the same object:
>>> 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]
5.3.11 Cloning lists
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]
5.3.12 Lists and for loops
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
for (i, val) in enumerate(xs):
xs[i] = val**2
Example
for (i, v) in enumerate(["banana", "apple", "pear", "lemon"]):
print(i, v)
OUTPUT
0 banana
1 apple
2 pear
3 lemon
5.3.13 List parameters
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]
>>> [Link](1, 12) # Insert 12 at pos 1, shift other items up
>>> mylist
[5, 12, 27, 3, 12]
>>> [Link](12) # How many times is 12 in mylist?
2
>>> [Link]([5, 9, 5, 11]) # Put whole list onto end of mylist
>>>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
5.3.15 Pure functions and modifiers
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]
5.3.16 Functions that produce lists
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
Initialize a result variable to be an empty list.
Loop.
Create a new element.
Append it to the result.
Return the result.
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
5.3.17 Strings and lists
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.
>>>song="The rain in Spain..."
>>>words=[Link]()
>>>words
['The', 'rain', 'in', 'Spain...']
An optional argument called a delimiter can be used to specify which string to
use as the boundary marker between substrings. The following example uses the
string "ai" as the delimiter:
>>> [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...'
5.3.18 list and range
>>> letters = list("Crunchy Frog")
>>> letters
["C", "r", "u", "n", "c", "h", "y", " ", "F", "r", "o", "g"]
>>> "".join(letters)
'Crunchy Frog
>>> range(10) # Create a lazy promise
range(0, 10)
>>> list(range(10)) # Call in the promise, to produce a list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python Programming Dept. ECE
5.3.19 Looping and lists
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())
5.3.20 Nested lists
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:
>>> nested = ["hello", 2.0, 5, [10, 20]]
If we output the element at index 3, we get:
>>> print(nested[3])
[10, 20]
Python Programming Dept. ECE
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
Nested lists are often used to represent matrices.
>>> mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Mx is a list with three elements, where each element is a row of the matrix. We
can select an entire row from the matrix in the usual way:
>>> mx[1]
[4, 5, 6]
Or we can extract a single element from the matrix using the double-index
form:
>>> mx[1][2]
6