So I’m trying to make a list of numbers that are multiples of 3, this is my code:

multiples_of_3 = []
for value in range(3, 31):
    number = value % 3 == 0
    multiples_of_3.append(number)

print(multiples_of_3)

But it transforms the results into booleans, which throws me a list with false and trues instead of numbers, what I’m doing wrong? I know comprehension lists exist and that this could be done more efficiently but well, I’m trying to learn and writing it as a comprehension list doesn’t make it easier.

  • string@fediverse.ro
    link
    fedilink
    arrow-up
    2
    ·
    2 years ago

    You are appending the result of the comparison value % 3 == 0 to the list multiples_of_3, which will always be either True or False. Instead, you should be appending value to the list if it is a multiple of 3. You can do this by changing the line multiples_of_3.append(number) to multiples_of_3.append(value) if the if statement number = value % 3 == 0 is true.

    • hotdaniel@lemmy.zip
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      1 year ago

      To add, OP could just use range(3,31,3) which increments by 3. Which reduces the loop enough that it becomes clear something like list comprehension would, yes, be easier.

      Edit: Didn’t realize this was 6 months old haha