def list_to_string(spam):
"""
Parameters
----------
spam: list
The input list.
Returns
-------
string: str
The ouput string.
"""
# coding your answer here
string = ""
for i in range(len(spam)):
if i != len(spam) - 1:
string = string + spam[i] + ", "
else:
string = string + "and " + spam[i]
return(string)
Appendix H — Assignment 3
H.1 (1) Suppose spam contains the list [‘a’, ‘b’, ‘c’, ‘d’]. What does spam[int(int('3' * 2) // 11)]
evaluate to?
- ‘a’
- ‘b’
- ‘c’
- ‘d’
Ans: Double click to answer the question
H.2 (2) Suppose bacon contains the list [3.14, ‘Sherry’, 18, ‘Sherry’, True]. What does bacon.append(100)
make to the list value in bacon look like?
- [100, 3.14, ‘Sherry’, 18, ‘Sherry’, True]
- [3.14, ‘Sherry’, 18, ‘Sherry’, True]
- [3.14, ‘Sherry’, 18, ‘Sherry’, True, 100]
- None of above
Ans: Double click to answer the question
H.3 (3) How would you assign the value 'hello'
as the third value in a list stored in a variable named computer?
- computer[3] <- ‘hello’
- computer[3] == ‘hello’
- computer[2] = ‘hello’
- computer[2] == ‘hello’
Ans: Double click to answer the question
H.4 (4) What is []
?
- dictionary
- tuple
- list
- dataframe
Ans: Double click to answer the question
H.5 (5) What are the operators for list concatenation and list replication?
- -, /
- +, **
- +, *
- -, //
Ans: Double click to answer the question
H.6 (6) What are two ways to remove values from a list?
Ans: Double click to answer the question
The del
statement and the remove()
list method are two ways to remove values from a list.
H.7 (7) What is the difference between lists and tuples?
Ans: Double click to answer the question
Lists are mutable; they can have values added, removed, or changed. Tuples are immutable; they cannot be changed at all. Also, tuples are written using parentheses, ( )
, while lists use the square brackets, [ ]
.
H.8 (8) What is the difference between copy.copy()
and copy.deepcopy()
?
Ans: Double click to answer the question
The copy.copy() function will do a shallow copy of a list, while the copy.deepcopy() function will do a deep copy of a list.
That is, only copy.deepcopy() will duplicate any lists inside the list.
H.9 (9) Write a function takes a list value as an argument and returns a string with all the items separated by comma and a space, with and inserted before the last item.
sample output:
If you enter a list ['Mathematics', 'computer', programming']
, then you should get Mathematics, computer, and programming
.
H.10 (10) Say you have a list of lists, grid
, where each value in the inner lists is a one-character string. Copy the grid value and write code that uses it to print the image.
sample output
. . 00 . 00 . .
. 0000000 .
. 0000000 .
. . 00000 . .
. . . 000 . . .
. . . . 0 . . . .
Hint:
In order to print the image, you will need to use a loop in a loop.