Python Forum
python 2D array creation and print issue
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python 2D array creation and print issue
#6
Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.

The obvious solution appears to be wrong:

a = [[0] * m] * n

This can be easily seen if you set the value of a[0][0] to 5, and then print the value of a[1][0] — it will also be equal to 5. The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list (just as well as the operation b = a for lists does not create the new list), so all rows in the resulting list are actually the same string.
Reply


Messages In This Thread
RE: python 2D array creation and print issue - by developerbrain - May-15-2019, 01:38 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  dynamic object creation using python gary 7 1,285 Oct-15-2022, 01:35 PM
Last Post: Larz60+
  Question: print issue python202209 3 971 Sep-18-2022, 11:51 AM
Last Post: jefsummers
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,165 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  how to print all data from all data array? korenron 3 2,481 Dec-30-2020, 01:54 PM
Last Post: korenron
  How to print array indexes? Mark17 6 2,768 Aug-03-2020, 04:26 PM
Last Post: Mark17
  Issue with creating an array of pixel data for PNG files in Google Colab The_Sarco 1 1,936 Apr-29-2020, 12:03 AM
Last Post: bowlofred
  Socket creation speed difference Python 2.7 / Python 3.7 PiAil 1 2,468 Feb-13-2019, 01:55 PM
Last Post: PiAil
  Print 2D Array dragu_stelian 3 2,721 Jan-27-2019, 06:09 PM
Last Post: aakashjha001
  python rrdtool graph creation issue anna 0 4,444 Sep-10-2018, 11:10 AM
Last Post: anna
  Issue using print statement in a thread bweiss1258 9 5,408 Jan-16-2018, 02:07 AM
Last Post: bweiss1258

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020