Reputation: 791
I have a simple code
a_list=[1,2,3,4,5]
a2_list=[]
for x in a_list:
a2_list.append(x*2)
and I get a2_list=[2,4,6,8,10]
If I write code like
a_list=[1,2,3,4,5]
a2_list=[]
for x in a_list:
a2_list.append(x*2)
print a2_list
I get
[2]
[2,4]
[2,4,6]
[2,4,6,8]
[2,4,6,8,10]
I want to make a list of lists to record each step
a_list=[1,2,3,4,5]
a2_list=[]
b_list=[]
for x in a_list:
a2_list.append(x*2)
b_list.append(a2_list)
I would like to get b_list = [[2],[2,4],[2,4,6],[2,4,6,8],[2,4,6,8,10]]
but I get b_list=[[2,4,6,8,10],[2,4,6,8,10],[2,4,6,8,10],[2,4,6,8,10],[2,4,6,8,10]]
It seems like a very easy problem, but I can't figure what I am doing wrong
Upvotes: 0
Views: 85
Reputation: 36
While the solutions above work fine, list.copy()
is not only more readable, but also faster as of Python 3.7. See this discussion on all the ways to copy a list. Therefore, this solution is the most intuitive to me.
a_list=[1,2,3,4,5]
a2_list=[]
b_list=[]
for x in a_list:
a2_list.append(x*2)
b_list.append(a2_list.copy())
b_list
Upvotes: 0
Reputation: 1084
This is because list
is mutable
object. You should learn about it. The possible solution is to copy the list as others suggested.
e.g.
a_list = [1,2,3,4,5]
a_list = list(a_list)
or
a_list = a_list[:]
There are other methods too.
Upvotes: 0
Reputation: 791
That works
a_list=[1,2,3,4,5]
a2_list=[]
b_list=[]
for x in a_list:
a2_list.append(x*2)
b = a2_list[:]
b_list.append(b)
Upvotes: 2