0

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

AK9309
  • 761
  • 3
  • 13
  • 33

2 Answers2

2

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)
AK9309
  • 761
  • 3
  • 13
  • 33
0

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.

Community
  • 1
  • 1
Mohammad Mustaqeem
  • 1,034
  • 5
  • 9