Building Lists in a Loop

Building Lists in a Loop

A loop can build a new list: start with an empty list, append one element per pass.

def doubled_all(numbers):
    result = []
    for number in numbers:
        result.append(number * 2)
    return result

print(doubled_all([3, 5, 8]))

Output:

[6, 10, 16]

This is the accumulator pattern with a list instead of a number: create result before the loop, grow it inside, return it after.

Adding an if inside the loop filters — only some elements make it into the new list:

def only_positive(numbers):
    result = []
    for number in numbers:
        if number > 0:
            result.append(number)
    return result

print(only_positive([4, -2, 7, -9]))

Output:

[4, 7]

Exercise

  1. Define a function named discounted_prices with one parameter, prices (a list of numbers).
  2. It returns a new list where every price over 100 is reduced by 10% (multiplied by 0.9), and every other price is kept as is.

discounted_prices([200, 50, 120]) returns [180.0, 50, 108.0].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestDiscountedPrices(unittest.TestCase):
    def test_mixed_prices(self):
        self.assertEqual(discounted_prices([200, 50, 120]), [180.0, 50, 108.0])

    def test_exactly_100_is_not_discounted(self):
        self.assertEqual(discounted_prices([100]), [100])

    def test_empty_list_gives_empty_list(self):
        self.assertEqual(discounted_prices([]), [])

    def test_original_list_is_not_changed(self):
        prices = [200, 50]
        discounted_prices(prices)
        self.assertEqual(prices, [200, 50])
def discounted_prices(prices):
    result = []
    for price in prices:
        if price > 100:
            result.append(price * 0.9)
        else:
            result.append(price)
    return result


print(discounted_prices([200, 50, 120]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.