Reputation: 347
Let's say I have a list
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to increase every 3rd number by a value of 5 to result in
A = [1, 2, 8, 4, 5, 11, 7, 8, 14, 10]
My gut tells me something along the lines of
A[::3] = [x + 5 for x in A]
OR using the loop below with replace somehow integrated
for num in range(0, len(A), 3):
A = num + 5
Send help...thanks in advance.
Upvotes: 0
Views: 72
Reputation: 103525
You almost had it with your first attempt.
Modify the slice to start at the 3rd element (index 2) per your example, and make sure to read the same slice that you're writing to:
A[2::3] = [x+5 for x in A[2::3]]
Upvotes: 1
Reputation: 446
You could make a function for it which would account for duplicate values or unsorted values. If my assumptions are not correct, you could easily adjust the function to get your values correct.
A = [1, 2, 3, 4, 5, 6, 10, 8, 9, 7]
def list_modifier(passed_list):
passed_list.sort()
mod_list = list(set(passed_list))
out_list = {i:i if (mod_list.index(i)+1)%3 != 0 else (i+5) for i in mod_list }
passed_list = [out_list[i] for i in out_list]
return passed_list
list_modifier(A)
Returned list looks like this: [1, 2, 8, 4, 5, 11, 7, 8, 14, 10]
Upvotes: 0
Reputation: 3054
i think this will do it
A=[x+5 if i%3==0 else x for i,x in enumerate(A,1)]
Upvotes: 0