Homework 6: List Homework
Complete each of the five excercises in CodingBat
For each of the following excercises:
-
Predict: First, complete the exercise without using the
Python interpreter. (You are welcome to refer to your notes or
textbook, read Python documentation, look at examples from class,
etc.; just don’t actually run any code.) We strongly encourage you to show some work here – if things go wrong, it is easier for us to provide useful feedback!
-
Check: Run the code. Does the actual output agree with what
you wrote down in step 1?
-
Evaluate: If your answer to part 1 was different than the
actual output, keep experimenting with it, consult the textbook or
Python documentation, ask a friend or TA or professor, etc. until
you can explain why the code works the way it does and what your
misunderstanding(s) were in part 1. (You do not need to do
anything for step 3 if the output agrees exactly with what you
wrote in step 1.)
Suppose that lst = [5, 7, 10, 2, 3].
Find the value of each expression:
-
lst[2]
-
lst[2:4]
-
lst[:3]
-
len(lst)
-
Consider the following code. What is printed by the final line,
print(mklist(5))?
def mklist(n):
nums = []
i = 0
p = 1
while (i <= n):
nums.append(p)
p *= 2
i += 1
return nums
print(mklist(5))
-
What is printed by the following code?
animals = ['caiman', 'bat', 'dingo', 'chihuahua', 'baboon', 'fox', 'galapagos']
i = 0
while i < len(animals):
if (animals[i][1] == 'a'):
print(animals[i])
i += 1