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
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]
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)
)
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
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]
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)
)