Zero
Zero

Reputation: 76917

Modifying List elements in a loop

Is it possible to update/modify the list elements/items in a loop. Here I have to modify items of t

n_wk=[1,2,3,2,3,4,2,3]
t=['a','a','a','a','a','a','a','a']

for i in range(len(n_wk)):
    if i==0:
        continue
    if n_wk[i]<n_wk[i-1]:
        if t[i]=='a':
            t[i]='b'
        elif t[i]=='b':
            t[i]='c'
    if n_wk[i]>n_wk[i-1]:
       t[i]=t[i-1]

I was expecting output t = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']. But, the output is coming out to be t=['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']. Seems like list t is not getting updated in the loop.

Can we not update item/elements of the list in a loop?

Upvotes: 1

Views: 166

Answers (2)

wookie919
wookie919

Reputation: 3134

Here's a method that does not loop using indexes and does not require t to be initialized with 'a's to begin with:

n_wk = [1,2,3,2,3,4,2,3]
t = []

n_prev = 0
t_prev = 'a'

for n in n_wk:
    t_new = t_prev
    if n < n_prev:
        if t_prev == 'a':
            t_new = 'b'
        elif t_prev == 'b':
            t_new = 'c'
    t.append(t_new)
    n_prev = n
    t_prev = t_new

print(t)

Upvotes: 0

dwitvliet
dwitvliet

Reputation: 7671

Your list t is indeed getting modified:

# t before loop
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
# t after loop
['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']

However, a slight change in your code will give you the result you are looking for:

for i in range(len(n_wk)):
    if i == 0:
        continue
    if n_wk[i] < n_wk[i-1]:
        if t[i-1] == 'a': #changed from t[i]
            t[i] = 'b'
        elif t[i-1] == 'b': #changed from t[i]
            t[i] = 'c'
    if n_wk[i] > n_wk[i-1]:
       t[i] = t[i-1]

print(t)
# ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']

Upvotes: 1

Related Questions