0

I have been programming for a while in Java and C++. However, I am trying to learn Python and I am trying to initialize a two-dimensional array in Python. Why does it take only the last two inputs?

I tried everything, but I can't understand why it is not working how it is supposed to be.

   def prog2():
        x = int(input('x> '))
        y = int(input('y> '))
        pole = [[0] * x] * y

        for a in range(x):
            for b in range(y):
                pole[a][b] = int(input('> '))

        print(pole)
    prog2()

When I define x and y as 2, and the following four inputs as 1, 2, 3, 4, I expect the output to be [[1, 2], [3, 4]]. However I am getting [[3, 4],[3, 4]]

x> 2
y> 2
> 1
> 2
> 3
> 4
[[3, 4], [3, 4]]

Thank you for your patience and help. :) I am a novice in Python.

Alec
  • 8,529
  • 8
  • 37
  • 63
Tomino
  • 475
  • 2
  • 15

3 Answers3

1

Change:

pole = [[0] * x] * y

To:

pole = [0 for _ in range(x)] * y

To understand it properly run this code:

lists = [[]] * 3
lists[0].append('hi')
print(lists)

Ouptut:

[['hi'], ['hi'], ['hi']]

[0] * x is evaluated only once and it creates a list. [[0] * x] * y creates a list containing y references of the same list.


Read more about the behavior in this StackOverflow question.

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
  • Thank you very much! This just seems very strange to me because I am used to typical C++ syntax of arrays. – Tomino Oct 08 '19 at 18:04
0
pole = [[0] * x] * y

Sets all of the inner memory addresses equal to each other (each index represents the same object)

Change your initialization:

pole = [0 for _ in range(x)] * y
Alec
  • 8,529
  • 8
  • 37
  • 63
0

You need copy.deepcopy(). When creating the members of the 2-d array you were copying over the same 1-d array object, so the assignment for pole[0][0] was assigning to pole[1][0] as well, etc.

#!/usr/bin/env python3
import copy
def prog2():
        x = int(input('x> '))
        y = int(input('y> '))
        pole = [[0] * x]
        for i in range(1, y):
            pole.append(copy.deepcopy(pole[0]))
        for a in range(x):
            for b in range(y):
                pole[a][b] = int(input('> '))

        print(pole)
prog2()
Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208