asqapro
asqapro

Reputation: 175

Looping copied list and deleting from original list deletes from copied list

The snippet of code that's messing up:

equ2 = ['+', '10', '+', '2', '-', '2', '+', '4']
flag4 = [ ]

for k in equ2[:]:
    if equ2[equ2.index(k)-1] == '+':
        del(equ2[equ2.index(k)])
        flag4.append('-' + k)
    elif equ2[equ2.index(k)-1] == '-':
        del(equ2[equ2.index(k)])
        flag4.append('+' + k)
print flag4

*Edit: I messed up the variables, sorry about that :x

*Edit2: Sorry again D: jedwards, that is the output I'm getting, I got the other output by deleting from the copied list

Output I'm getting:

['-10', '-2', '--', '-2', '-4']

Output I want:

['-10', '-2', '+'2, '-4']

I figured out that when it got to the '-', it checks the original list (now modified to + - 2 + 4), and sees that the item before the '-' is a '+', so it appends '--', then checks the original list again (now + 2 + 4) and sees the '+' before the 2, so it appends '-2' (fixes itself sorta after that). Is it checking the original list the whole time?

Upvotes: 0

Views: 118

Answers (2)

jedwards
jedwards

Reputation: 30210

I'm not really conviced this is the best way to do this, the following works

equ2 = ['+', '10', '+', '2', '-', '2', '+', '4']
flag4 = list()

chgsgn = dict([('+','-'), ('-','+')])

while len(equ2):
    sgn = equ2.pop(0)
    num = equ2.pop(0)

    flag4.append(chgsgn[sgn] + num)


print flag4

Which outputs

['-10', '-2', '+2', '-4']

Edit: Alternatively, using list comprehensions and not modifying equ2:

chgsgn = dict([('+','-'), ('-','+')])
flag4 = [chgsgn[sgn]+num for (sgn,num) in zip(*[iter(equ2)]*2)]
print flag4

Which also outputs

['-10', '-2', '+2', '-4']

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304255

The indices you are trying to modify are out of sync after the first element is deleted from the list.

There are better ways to loop pairwise, but it's not clear to me what the loop is supposed to do in the general case

eg.

>>> flag4 = [dict(['+-','-+'])[i] + j for i,j in zip(*[iter(equ2)]*2)]
>>> print flag4
['-10', '-2', '+2', '-4']

Upvotes: 2

Related Questions