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

Module 2.2

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

Module 2.2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

LIST

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 = ["apple", "banana", "cherry"]


b = ["Ford", "BMW", "Volvo"]
a.append(b)
List length
• The function len returns the length of a list.
words = [“hen", “cat", “duck", “cow"]
i=0
>>> a=[1,2,2,3]
while i < len(words): >>> len(a)
4
print words[i]
i=i+1
• Although a list can contain another list, the nested list still counts as a
single element.
• The length of this list is four:
[ ‘cat’, 1, [’dog’, ’cow’, ’hen’] , [1, 2, 3] ]
List membership
• Boolean operator that tests membership in a sequence.
>>> words = [“hen", “cat”, “duck", “cow”]
>>> ‘cat’ in words
True
>>> ‘goat’ in words
False
• We can use the not in combination with in to test whether an element is not
a member of a list:
>>> ‘goat’ not in words
True
Lists and for loops
• The generalized syntax of a for loop is: a1=[1,2,2,3]
for VARIABLE in LIST: for a in a1:
BODY print(a)

This statement is equivalent to:


i=0
i=0
while i < len(LIST): while i < len(LIST):
VARIABLE = LIST[i] print (LIST[i])
print (VARIABLE) i=i+1
i=i+1
a=[1,2,2,3]
for a in a:
print(a)

Any list expression can be used in a for loop:


for number in range(20):
if number % 2 == 0:
print number

for fruit in ["banana", "apple", “mango"]:


print ("I like to eat") + fruit + ("s!")
List operations
• The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
• Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
a=[1,2,3,4.0]
[0, 0, 0, 0] a*3
>>> [1, 2, 3] * 3 [1, 2, 3, 4.0, 1, 2, 3, 4.0, 1, 2, 3, 4.0]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
• The first example repeats [0] four times.
• The second example repeats the list [1, 2, 3] three times.
List slices
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
>>> list[ :4]
[’a’, ’b’, ’c’, ’d’]
>>> list[3: ]
[‘d’, ‘e’, ‘f’]
• If you omit the first index, the slice starts at the beginning.
• If you omit the second, the slice goes to the end.
• So if you omit both, the slice is really a copy of the whole list.
>>> list[ : ]
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
Lists are Mutable
• Unlike strings, lists are mutable, which means we can change their
elements.
• Using the bracket operator on the left side of an assignment, we can update
one of the elements:
>>> fruits = ["banana", "apple", “mango"] >>> a=[1,2,3,4]
>>> a[1:3]=40,50
>>> fruits[0] = “watermelon" >>> a
[1, 40, 50, 4]
>>> fruits[-1] = "orange"
>>> a[1:3]=[40,50] # also valid
>>> print fruits
[’ watermelon’, ’apple’, ’orange’]
With the slice operator we can update several elements at once:
List Updation
list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> list[1:3] = [‘x’, ‘y’]
>>> print list
[‘a’, ‘x’, ‘y’, ‘d’, ‘e’, ‘f’]
• We can also remove elements from a list by assigning the empty list to
them:
>>> list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> list[1:3] = []
>>> print list
[‘a’, ‘d’, ‘e’, ‘f’]
• And we can add elements to a list by squeezing them into an empty slice at
the desired location:
>>> list = [‘a’, ‘d’, ‘f’]
>>> list[1:1] = [’b’, ’c’]
>>> a=[1,2,3,4.0]
>>> print list >>> a[1:1]=['new1','new2']
[’a’, ’b’, ’c’, ’d’, ’f’] >>> print(a)
>>> list[4:4] = [’e’] [1, 'new1', 'new2', 2, 3, 4.0]
>>> print list
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
List deletion
• del removes an element from a list:
>>> a = [’one’, ’two’, ’three’]
>>> del a[1]
>>> a
[’one’, ’three’]
• You can use a slice as an index for del:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> del list[1:5]
>>> print list
[’a’, ’f’]
As usual, slices select all the elements up to, but not including, the second
index.
Objects and values
• If we execute these assignment statements,
a = "banana"
b = "banana"
• We know that a and b will refer to a string with the letters "banana". But
we can’t tell whether they point to the same string.
• In one case, a and b refer to two different things that have the same value.
• In the second case, they refer to the same thing. These “things” have
names—they are called objects.
• Every object has a unique identifier, which we can obtain with the id
function.
• By printing the identifier of a and b, we can tell whether they refer to the
same object.
>>> id(a)
135044008
>>> id(b)
135044008
• In fact, we get the same identifier twice, which means that Python only
created one string, and both a and b refer to it.
• Interestingly, lists behave differently. When we create two lists, we get two
objects:
>>> a = [1, 2, 3] >>> a="apple"
>>> b="apple"
>>> b = [1, 2, 3] >>> c=[1,2]
>>> d=[1,2]
>>> id(a) >>> id(a)
135045528 1381447224624
>>> id(b)
>>> id(b) 1381447224624
>>> id(c)
135041704 1381446988096
>>> id(d)
1381446981440

• 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’)

* 'tuple' object doesn't support item deletion


Tuple assignment
• Once in a while, it is useful to swap the values of two variables.
• With conventional assignment statements, we have to use a temporary
variable.
>>> A=10
• For example, to swap a and b: >>> B=20
>>> temp = a >>> A,B=B,A
>>> print(A)
>>> a = b 20
>>> print(B)
>>> b = temp 10
• If we have to do this often, this approach becomes cumbersome.
• Python provides a form of tuple and list assignment that solves this
problem neatly:
>>> a, b = b, a
• The left side is a tuple / list of variables;
the right side is a tuple / list of values.
• Each value is assigned to its respective variable. All the expressions on the
right side are evaluated before any of the assignments. This feature makes
tuple assignment quite versatile.
• Naturally, the number of variables on the left and the number of values on
the right have to be the same:
>>> a, b, c, d = 1, 2, 3
• ValueError: unpack tuple of wrong size
Tuples as return values
• Functions can return tuples as return values. For example, we could write
a function that swaps two parameters: def swap(a,b):
return(b,a)
def swap(x, y): a,b=10,20 a = 20 b = 10
a,b=swap(a,b)
return y, x print('a = ', a, 'b = ',b)
• Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)

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

You might also like