Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

list - What is the different between list1.append(list2) and list1.append(list2[:]) in a for loop in Python?

Here are two pieces of similar codes:

s='abc'
ans,res=[],[]
for i in range(len(s)):
    ans.append(i)
    res.append(ans[:])
print(res,"
")

Result: [[0], [0, 1], [0, 1, 2]]

ans,res=[],[]
for i in range(len(s)):
    ans.append(i)
    res.append(ans)
print("
",res)

Result: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

I am confused about the difference between the two results. Why do res.append(ans) and res.append(ans[:]) lead to different return value?

Could anyone give me some hints or tell me any underlying logic that I ignored?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
s='abc'
ans,res=[],[]
for i in range(len(s)):
    ans.append(i)
    res.append(ans[:])
print(res,"
")

This appends ans as the next item of list. If you see how ans and res change every iteration, you will understand how its is working. Changes:

Iteration-0                   
ans- [0]
res- [[0]]

Iteration-1
ans- [0, 1]
res- [[0], [0, 1]]

Iteration-2
ans- [0, 1, 2]
res- [[0], [0, 1], [0, 1, 2]]

And for the other one:

ans,res=[],[]
for i in range(len(s)):
    ans.append(i)
    res.append(ans)
print("
",res)

This overwrites the complete list every iteration like:

Iteration-0
ans- [0]
res- [[0]]
Iteration-1
ans- [0, 1]
res- [[0, 1], [0, 1]]
Iteration-2
ans- [0, 1, 2]
res- [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...