Home>

Adding a 2D array does not work as expected.
Why?

The environment is
Python 3.8.5
anaconda

a = []
b = []
for i in range (1,11):
  a.append (i)
  if i% 5 = 0:
Print (a)
     # 1st time: a = [1,2,3,4,5]
     # 2: a = [6,7,8,9,10]
     b. append (a)
Print (b)
     # 1st time: b = [[1,2,3,4,5]]
# 2nd time: b = [[6,7,8,9,10], [6,7,8,9,10]]
     a.clear ()
print (b)
#b = [[], []]

As mentioned above, the list added first will be overwritten and added.
Moreover, it becomes empty when the for statement is exited.
No wonder.

Please write the result of trying in your environment or the solution.

The assumption is
b = [[1,2,3,4,5], [6,7,8,9,10]]
is.

Is it due to the version?

  • Answer # 1

    A story addicted to copying the list I think that will be helpful.
    The following is an example of countermeasures

    a = []
    b = []
    for i in range (1,11):
        a.append (i)
        if i% 5 == 0:
            b.append (a [:])
            a.clear ()
    print (b)
    # [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

    Although it is a snake, it is convenient to use numpy etc. for array operation.

    import numpy as np
    a = np.array (range (1,11))
    b = a.reshape ([-1,5])
    print (b)
    # [[1 2 3 4 5]
    # [6 7 8 9 10]]

  • Answer # 2

    The question code contains double-byte spaces,
    It cannot be executed because == becomes =.
    Copy and paste the code that is working.

    a.clear ()Toa = []It would be good to set it to.
    Do you know why?