Replacing negative values

The four versions of remove_negatives in Listing 1 should:

  1. Receive a list of integers.
  2. 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?

Listing 1: Alternatives for the remove_negatives function that returns a copy of a list with the negative values replaced by zero (Question 1).
(a)
def remove_negatives(numbers):
    # Build the list to return.
    result = []

    for number in numbers:
        if number < 0:
            result.append(0)
        else:
            result.append(number)

    return result
(b)
def remove_negatives(numbers):
    # Build the list to return.
    result = []

    for i in range(len(numbers)):
        if numbers[i] < 0:
            numbers[i] = 0

    return result
(c)
def remove_negatives(numbers):
    # Build the list to return.
    result = []

    for i in range(len(result)):
        if numbers[i] < 0:
            result.append(0)
        else:
            result.append(numbers[i])

    return result
(d)
def remove_negatives(numbers):
    # Build the list to return.
    result = []

    for number in numbers:
        if number < 0:
            result.append(0)

    return result
  • len(items) returns the number of items, without changing the collection. len([8, 3]) is 2; len([]) is 0. For nested lists, it counts the outer items only.
  • range(start, stop, step) supplies integers from start toward, but excluding, stop.
    • step defaults to 1, and range(stop) starts at 0.
    • 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.
  • list collects the supplied values in a new list.
  • items.append(value) adds one item at the end of the list and returns None. Starting with items = [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.