Reputation: 17
I don't know how to update the value. I want next value is only greater 1 than previous value.
In this code 4
will change to 3
, great. Since 4
changed to 3
so I expect 5
will change to 4
...
my_list = [1, 2, 4, 5, 6, 7, 1, 2, 3, 4, 5]
for i, curr_item in enumerate(my_list):
prev_item = my_list[i - 1] if i >= 1 else 0
if curr_item - prev_item > 1:
print(curr_item) # -> 4
curr_item = prev_item + 1
I got this
[1, 2, 3, 5, 6, 7, 1, 2, 3, 4, 5]
expected
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]
Upvotes: 0
Views: 1036
Reputation: 31304
you are setting the curr_item
(and i
) with the for
clause in each iteration. you are free to do whatever you want with those variables, but at the beginning of the next iteration they will be set again.
i'm just re-writing your code to make this a bit clearer:
for x, y in enumerate(my_list):
i = x
curr_item = y
prev_item = my_list[i - 1] if i >= 1 else 0
if curr_item - prev_item > 1:
curr_item = prev_item + 1
so whatever you do to curr_item
in your loop body will be lost in the next iteration.
Upvotes: 0
Reputation: 13939
You need to update my_list[i]
(not curr_item
):
my_list = [1, 2, 4, 5, 6, 7, 1, 2, 3, 4, 5]
for i, curr_item in enumerate(my_list):
prev_item = my_list[i - 1] if i >= 1 else 0
if curr_item - prev_item > 1:
print(curr_item) # -> 4
my_list[i] = prev_item + 1
print(my_list) # [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]
Writing curr_item = prev_item + 1
assigns prev_item + 1
to the name curr_item
; here, curr_item
is not something like a pointer in C.
If you want a non-destructive way, the following makes a new list:
output = []
prev = 0
for x in my_list:
if x - prev > 1:
prev = prev + 1
else:
prev = x
output.append(prev)
print(output) # [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]
Alternatively, using list comprehension and walrus operator:
prev = 0
output = [prev := (prev + 1 if x - prev > 1 else x) for x in my_list]
print(output) # [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]
Upvotes: 2