How do I make a list of the same variable with different values? python

Viewed 267

I am a complete newbie and this might be a dumb question: I need to make a list of the values as u can see down here. I will most likely need a for loop using append from what I have read till now but I cant really grasp how to do it in my case. I want to start with the min value 23 and increment by 2 until I reach the max 31 And I would need to be able to change the values in the for loop for future changes The +3 has to be added everytime regardless It would be great if someone could help me.

arrivalDistance = meanSpeed * (23 + 3)
arrivalDistance2 = meanSpeed * (25 + 3)
arrivalDistance3 = meanSpeed * (27 + 3)
arrivalDistance4 = meanSpeed * (29 + 3)
arrivalDistance5 = meanSpeed * (31 + 3)
3 Answers
arrivalDistance = [meanSpeed * (23+i +3) for i in range(0, 9, 2)]

This will create a list called arrivalDistance that will loop over the range [0, 9) with a step of 2. So it will get you the numbers 0, 2, 4, 6, 8 and add them to your value. This is called list comprehension and lets you avoid using a for loop, since it's already one.

arrivalDistanceList = []

for i in range(23,32,2):
    arrivalDistanceList.append(meanSpeed * (i + 3))

The syntax of for loop

for iterator in range(startValue, endValue + 1, increment)

The third parameter is increment which increment the sequence by given value.

Hope you got the answer

Instead of evaluating the + 3 and + 23 at each variable, you can use a loop, and directly add the numbers to the parameters of the loop:

a = 23 + 3
b = 5
step = 2
arrivalDistance = [meanSpeed * i for i in range(a, a + b * step, step)]

So a is the starting value, b is the additional value, c is the number of variables and step is the increment amount.

Related