2. Compare and contrast strings, lists, and tuples. For example, consider what t
ID: 3775496 • Letter: 2
Question
2. Compare and contrast strings, lists, and tuples. For example, consider what they can hold and what operations can be done on the data structures.
3. Consider the following code:
list_var = [] for i in
range (0, 6, 2) : for
k in range (4) :
list_var.append (i + k)
print(i) # Line 1
print(k) # Line 2
print(list_var) # Line 3
(a) What is printed by Line 1?
(b) What is printed by Line 2?
(c) What is printed by Line 3?
4. Tuples resemble lists in many ways. However, as an immutable type, the ways in which they can be interacted with are limited. Take the following statements. What will happen if you try to add to the tuple in the manner shown? How can you rewrite the code to achieve the intended result?
tuple_var = ()
for i in range (10) :
tuple_var += i
9. Write a function power that takes in a base and an exp and recursively computes base*exp. You are not allowed to use the ** operator.
10. Provide two small numbers for base and exp in function power, and draw the figure to trace the recursive function calls.
Explanation / Answer
1. A string is a sequence of characters. You can access the characters one at a time with the bracket operator.
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items.
A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
2. a. line 1 prints the updated i variable after every loop.
b. line 2 prints the updated k variable after every loop.
c. line 3 prints the updated list after every loop.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.