chyanog
chyanog

Reputation: 619

A strange behavior when I append to a list in Python

I am looking for the Josephus_problem ,but the result is not my Expected. Why?

def J(n,x):
    li=range(1,n+1)
    k=0
    res=[]
    while len(li)>1:
        k= (x+k-1) % len(li)
        li.pop(k)
        res.append(li)
        #print li
    return res

print J(5,3)

Expected Output:

[1, 2, 4, 5]

[2, 4, 5]

[2, 4]

[4]

Actual Output:

[[4], [4], [4], [4]]

Upvotes: 3

Views: 194

Answers (1)

Oleksii Kachaiev
Oleksii Kachaiev

Reputation: 6234

You need to append copy of list here:

res.append(li[:]) # <-- not res.append(li) !!!

The actual reason of what's going on it that list is mutable data structure in Python. Look at this snippet

>>> l = [1,2,3]
>>> p = [l,l,l]    
>>> p
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> l.pop()
3
>>> p
[[1, 2], [1, 2], [1, 2]]

Upvotes: 5

Related Questions