Add 3 to value every time in a list

Question:

number= [value+3 for value in range (3,31)]
print (number)

I don’t know why the value doesn’t add 3 every time. The output goes like 6,7,8,9 etc

Asked By: Olivia Blanchett

||

Answers:

You need to declare the step value within range (the third argument). This argument tells range how much to increment itself at each step.

Code:

number = [value for value in range(3,31,3)]
print(number)

Output:

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
Answered By: Ryan

The code you have written does add 3 each time. What the code does is go through each number between 3 and 31 and add 3 to it:

3+3 = 6
4+3 = 7
5+3 = 8
6+3 = 9 etc.

I suspect what you want is for it to output to increment by 3 each time instead (6, 9, 12 etc). There are many different ways to achieve this, as Ryan mentioned range has a step option to do this easily.

Alternatively, you can still use a calculation in list comprehenstion, but instead of doing value+3, you can do value*3, but you will need to floor divide your original limits by 3 (so going from range(3,31) to range(1,10)):

number = [value*3 for value in range(1, 10)]
print(number)
[3, 6, 9, 12, 15, 18, 21, 24, 27]

(NB: If you want to change the 31 value without having to work out each time, you can use floor divide of 31//3, so range(1, 31//3))

Answered By: Emi OB
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.