CSC111 Examples of Operations on Lists
--D. Thiebaut (talk) 10:25, 25 March 2014 (EDT)
Important Behavior of Lists
Part 1: Passing Variables
# ListFunctions.py
# some functions that use lists
#
def box( caption ):
length = len( caption )+2
print( "\n\n\n+" + "-"*length + "+" )
print( "| " + caption + " |" )
print( "+" + "-"*length + "+\n" )
# change a number from negative to positive
# Version 1 returns the variable that was passed as a parameter
# Version 2 does not (it is not valid code)
def makeIntPositiveV1( x ):
if x < 0:
x = -x
return x
def makeIntPositiveV2( x ):
if x < 0:
x = -x
def main():
# -------------------------------------------------------
x = -5
print( "x = ", x )
x = makeIntPositiveV1( x )
print( "after calling makeIntPositiveV1(): x = ", x )
x = -5
print( "x = ", x )
makeIntPositiveV2( x )
print( "after calling makeIntPositiveV2(): x = ", x )
main()
- Output
x = -5 after calling makeIntPositiveV1(): x = 5 x = -5 after calling makeIntPositiveV2(): x = -5
Part 2: Passing List
# change all negative numbers in L to positive values
# Version 1 returns the list after having modified it
# Version 2 does not return the list (correct code)
def makePositiveV1( L ):
for i in range( len( L ) ):
if L[i] < 0:
L[i] = -L[i]
return L
def makePositiveV2( L ):
for i in range( len( L ) ):
if L[i] < 0:
L[i] = -L[i]
def main():
# -------------------------------------------------------
Lorg = [ -1, 2, 3, 4, -5, 6]
L = Lorg[:]
print( "L = ", L )
L = makePositiveV1( L )
print( "after calling makePrositiveV1:", L )
L = Lorg[:]
print( "L = ", L )
makePositiveV2( L )
print( "after calling makePrositiveV2:", L )
main()
- Output
L = [-1, 2, 3, 4, -5, 6] after calling makePrositiveV1: [1, 2, 3, 4, 5, 6] L = [-1, 2, 3, 4, -5, 6] after calling makePrositiveV2: [1, 2, 3, 4, 5, 6]