Python multi-dimensional array initialization code

Source: Internet
Author: User

In Python, initialize an array of 5x3 and each item is 0. The best method is:
Multilist=[[0ForColInRange (5)]ForRowInRange (3)]
We know that to initialize a one-dimensional array, we can do this:
Alist=[0]* 5
Yes, can we do this when initializing a two-dimensional array:
Multi=[[0]* 5]* 3
In fact, this is not correct, because [0] * 5 is an object in a one-dimensional array, and * 3 only copies the object reference three times. For example, modify multi [0] [0]:
Multi=[[0]* 5]* 3
Multi [0] [0]= 'Love China'
PrintMultiThe output result is:
[['Love China', 0, 0, 0, 0], ['Love China', 0, 0, 0], ['Love China', 0, 0, 0, 0]
We modified multi [0] [0], but modified our multi [1] [0] and multi [2] [0. This is not the expected result.

If we write it like this:
Multilist=[[0]* 5 ForRowInRange (3)]
Multilist [0] [0]= 'Love China'
PrintMultilistThe output result is as follows:
[['Love China', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]
Well, no problem. However, because the * method is easy to cause confusion and causes bugs, we recommend that you use the first method, namely:
Multilist=[[0ForColInRange (5)]ForRowInRange (3)]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.