Module 2.2
Module 2.2
Lists
• A list is an ordered set of values, where each value is identified by an
index.
• The values that make up a list are called its elements.
• Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type.
List values
• There are several ways to create a new list.
• The simplest is to enclose the elements in square brackets [ ]
[10, 20, 30, 40]
[“cat", “cow", “duck"]
• The first example is a list of four integers.
• The second is a list of three strings.
• The elements of a list don’t have to be the same type.
• The following list contains a string, a float, an integer, and another list:
["hello", 2.0, 5, [10, 20]]
• A list within another list is said to be nested list.
Lists contain consecutive integers
• Lists that contain consecutive integers are common, so Python provides a
simple way to create them:
>>> range(1,5) list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4]
• If there is a third argument, it specifies the space between successive values,
which is called the step size.
• This example counts from 1 to 10 by steps of 2:
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
Empty list
• Finally, there is a special list that contains no elements.
• It is called the empty list, and it is denoted [].
Eg- words= ['cat', 'windows', 'elephant’]
numbers = [17, 123]
empty = []
print (words, numbers, empty)
OUTPUT : [’cat’, ’windows’, ’elephant’] [17, 123] [ ]
• Adding elements to empty list
1. a=[]
>>> a.append(1)
>>> a
[1]
2. a.insert(2,15) ….. (Index, value)
Accessing elements
• The syntax for accessing the elements of a list is the same as the syntax for
accessing the characters of a string—the bracket operator [ ]
• The expression inside the brackets specifies the index.
• Remember that the indices start at 0:
number=[1,2,3]
print(number[0])
Output- 1
The bracket operator can appear anywhere in
an expression. When it appears on the left side
number=[1,2,3] of an assignment, it changes one of the
print(number[0]) elements in the list
number[1]=5
print(number) output - [1, 5, 3]
• Any integer expression can be used as an index:
>>> numbers[3-2] # same as number[1]
5
>>> numbers[1.0]
TypeError: sequence index must be integer
• If you try to read or write an element that does not exist, you get a runtime
error:
>>> numbers[3] = 5
IndexError: list assignment index out of range
• If an index has a negative value, it counts backward from the end of the
list: number=[10,20,30] Output
print(number[-1]) 30
print(number[-2]) 20
print(number[-3]) 10
List traversal
• It is common to use a loop variable as a list index.
words = [“hen", “cat", “duck", “cow"]
i=0
while (i < 4):
print (words[i])
i=i+1
• This while loop counts from 0 to 4.
• When the loop variable i is 4, the condition fails and the loop terminates.
• So the body of the loop is only executed when i is 0, 1, 2, and 3.
• Each time through the loop, the variable i is used as an index into the list,
printing the ith element. This pattern of computation is called a list traversal.
List append() Method
• The append() method appends an element to the end of the list.
• fruits = ['apple', 'banana', 'cherry’]
fruits.append("orange")
• a and b have the same value but do not refer to the same object.
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
• 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
>>> print a
[5, 2, 3]
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[:]
>>> print 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.
• Now we are free to make changes to b without worrying about a:
>>> b[0] = 5
>>> print a
[1, 2, 3]
List parameters
• Passing a list as an argument actually passes a reference to the list, not a
copy of the list.
• For example, the function head takes a list as an argument and returns the
first element:
• def head(list):
return list[0]
• Here’s how it is used:
>>> numbers = [1, 2, 3]
>>> head(numbers)
1
• If a function modifies a list parameter, the caller sees the change.
• For example, deleteHead removes the first element from a list:
def deleteHead(list):
del list[0]
• Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers
[2, 3]
• If a function returns a list, it returns a reference to the list.
• For example, tail returns a list that contains all but the first element of the
given list removed:
def tail(list):
return list[1:]
• Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print (rest)
[2, 3]
• Because the return value was created with the slice operator, it is a new list.
• Creating rest, and any subsequent changes to rest, have no effect on
numbers.
Nested lists
• A nested list is a list that appears as an element in another list. In this list, the
third indexed element is a nested list:
>>> list = ["hello", 2.0, 5, [10, 20]]
• If we print list[3], we get [10, 20]. To extract an element from the nested list,
we can proceed in two steps:
>>> t1 = list[3]
>>> t1[0]
10
Or we can combine them:
>>> list[3][1]
20
• Bracket operators evaluate from left to right, so this expression gets the thrid
element of list and extracts the one-th element from it.
Matrices
• Nested lists are often used to represent matrices.
• For example, the matrix: might be represented as:
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• matrix 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:
>>> matrix[1]
[4, 5, 6]
• Or we can extract a single element from the matrix using the double-index
form:
>>> matrix[1][1]
5
• The first index selects the row, and the second index selects the column.
Strings and lists
• Two of the most useful functions in the string module.
1. The split function breaks a string into a list of words.
• By default, any number of whitespace characters is considered a word
boundary:
import string
song = "The rain in Spain..."
print (str.split(song))
OUTPUT
[‘The’, ‘rain’, ‘in’, ‘Spain...’]
1.2. Delimiter
• An optional argument called a delimiter can be used to specify which
characters to use as word boundaries.
• The following example uses the string ‘ai’ as the delimiter:
• >>> str.split(song, ‘ai’)
[’The r’, ’n in Sp’, ’n...’]
• Notice that the delimiter doesn’t appear in the list.
2. Join function
• The join function is the inverse of split.
• It takes a list of strings and concatenates
• The elements with a space between each pair:
import string
str=‘ ’
list1=['The','rain','in','Spain...'] OUTPUT : The rain in Spain...
print(str.join(list1))
Tuples
Mutability and tuples
• So far, you have seen two compound types: strings, which are made up of
characters; and lists, which are made up of elements of any type.
• One of the differences we noted is that the elements of a list can be
modified, but the characters in a string cannot.
• In other words, strings are immutable and lists are mutable.
• There is another type in Python called a tuple that is similar to a list except
that it is immutable.
• Syntactically, a tuple is a comma-separated list of values:
>>> tuple = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
• Although it is not necessary, it is conventional to enclose tuples in
parentheses:
>>> tuple = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
• To create a tuple with a single element, we have to include the final comma:
>>> t1 = (’a’,)
>>> type(t1)
<class ‘tuple’>
• Without the comma, Python treats (’a’) as a string in parentheses:
>>> t2 = (’a’)
>>> type(t2)
<class ’str’>
• The index operator selects an element from a tuple.
>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)
>>> tuple[0]
’a’
• And the slice operator selects a range of elements.
>>> tuple[1:3]
(’b’, ’c’)
• But if we try to modify one of the elements of the tuple, we get an error:
>>> tuple[0] = ‘A’
TypeError: object doesn’t support item assignment
• Of course, even if we can’t modify the elements of a tuple, we can replace
it with a different tuple:
>>> tuple = (’A’,) + tuple[1:]
>>> tuple
(’A’, ’b’, ’c’, ’d’, ’e’)
Random numbers
• Python provides a built-in function that generates pseudorandom
numbers, which are not truly random in the mathematical sense, but for our
purposes they will do.
• The random module contains a function called random that returns a
floating-point number between 0.0 and 1.0. Each time you call random, you
get the next number in a long series. To see a sample, run this loop:
import random
for i in range(10):
x = random.random()
print x
List of random numbers
• The first step is to generate a list of random values.
• randomList takes an integer argument and returns a list of random
numbers with the given length.
• It starts with a list of n zeros. Each time through the loop, it replaces one
of the elements with a random number. The return value is a reference to
the complete list:
def randomList(n):
s = [0] * n
for i in range(n):
s[i] = random.random()
return s
We’ll test this function with a list of eight elements.
>>> randomList(8)
• 0.15156642489
• 0.498048560109
• 0.810894847068
• 0.360371157682
• 0.275119183077
• 0.328578797631
• 0.759199803101
• 0.800367163582