Replacing negative values
The four versions of remove_negatives in Listing 1 should:
- Receive a list of integers.
- Return a new list of the same length with each negative value replaced by
0.
The input list must remain unchanged. For example, if numbers is [1, -2, 3, -4, 5], the function should return [1, 0, 3, 0, 5] while numbers remains [1, -2, 3, -4, 5].
Which implementation of the remove_negatives function in Listing 1 correctly returns the required copy without modifying the input list?
remove_negatives function that returns a copy of a list with the negative values replaced by zero (Question 1).
TipHint
len(items)returns the number of items, without changing the collection.len([8, 3])is2;len([])is0. For nested lists, it counts the outer items only.range(start, stop, step)supplies integers fromstarttoward, but excluding,stop.stepdefaults to1, andrange(stop)starts at0.list(range(2, 7, 2))is[2, 4, 6];list(range(5, 1, -2))is[5, 3].- A range is empty when the step cannot reach the stop; a zero step raises
ValueError.
listcollects the supplied values in a new list.items.append(value)adds one item at the end of the list and returnsNone. Starting withitems = [8],items.append(3)changes it to[8, 3]. An appended list remains one nested item; an empty list accepts its first item the same way.