Lists


Preface


Basics

stuff = []

makes stuff a list with no elements.

stuff = [ 'abc', 1112, math.pi, ]

initializes stuff to be a three-element list, the first element has the string 'abc' as its value, the second element has value 1112, and the last element has value math.pi.

b1 = (x in stuff )

b2 = (x not in stuff )

sets b1 to be True or False depending whether x is an element of stuff, and sets b2 to be True or False depending whether x is not an element of stuff.

n = len( stuff )

sets the n to be the number of elements in stuff.

largest = max( stuff )

smallest = min( stuff )

sets largest and smallest respectively to the maximum and minimum value in stuff.

stuff.append( v )

adds v to the end of list stuff.

stuff[ x ] = v

sets the xth element of stuff to have value v


Patterns

total = 0

for nbr in numbers :

    total = total + nbr

print( total )

prints the sum of the elements in numbers.

numbers = []

for s in inputs :

    nbr = int( s )

    numbers.append( nbr)

print( numbers )

prints the inputs as a list of integers.

for nbr in numbers :

nbr = abs( nbr )

Why you say? What the code does is repeatedly set nbr to be the absolute value of its current value. Doing so does not change numbers. However, the following code does work.

n = len( numbers )

for i in range( 0, n ) :

numbers[ i ] = abs( numbers[ i ] )

Why you say again? Because each iteration another list element of numbers is updated to be the absolute value of its currrent value.

new_string = ''

for s in stuff

    c = ... # depends on what we want out of s

    new_string = new_string + c

print( new_string )

prints the new string.

 


 

 

 
   
   
   
 
  © 2019 Jim Cohoon   Resources from previous semesters are available.