1

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?

3
  • Clearly t is updated in the loop, since you replaced a values with b values. Your expectation of when the elif matches is incorrect. Commented Mar 25, 2013 at 20:58
  • Use a list comprehension and make a new list instead. Looping by index is unpythonic - slow, hard to read and inflexible. Commented Mar 25, 2013 at 21:00
  • Shouldn't the value of print t[i] in the if n_wk[i]<n_wk[i-1]: at i=5 be 'b'. But, I checked it. It's coming out as 'a'. Commented Mar 25, 2013 at 21:03

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.