a =[0, 0, 2, 4, 6]
This a list (a) and a fix value (x).
I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words result should like below:
while counter < x:
for i in a:
if i >0:
elif i ==0:
I think this does mostly what you want (at least, as I understand the question)...
def make_it_so(a, x): i = 0 counter=0 while counter < x: for i in a: if i == 0: yield 0 else: yield i + counter * x counter = counter + 1 # Demo for item in make_it_so([0, 0, 2, 4, 6], 5): print item
Note that I've made it a generator function. You could easily turn it into a regular function that returns a list if you created an output list at the top of the function and swapped
yield ... for
output_list.append(...) and then
return output_list at the end of the function...
The key here is to understand that after the first loop, you are adding
0 to all of the (non-zero) items. After the second loop, you are adding
x. After the third loop, you're adding the
x + x (since the first loop added
x and now you're adding
x more). In general, for the Nth loop, you'll be adding
(N-1) * x to all of the non-zero items. So, you just need to keep track of
N-1). In fact, your original code was already doing this (with
counter), so we just re-purpose that and it's all good.