Python initializes multidimensional array code _python

Source: Internet
Author: User
Tags in python
The best way to initialize an array of 5 x 3 per 0 in Python is to:
Multilist = [[0 for Col in range (5)] for row in range (3)]< /c15>

We know that in order to initialize a one-dimensional array, we can do this:
Alist = [0] * 5

Yes, so when we initialize a two-dimensional array, can we do this:
Multi = [[0] * 5] * 3

In fact, this is wrong, because [0] * 5 is a one-dimensional array of objects, * 3 words just copy the object's Reference 3 times, for example, I modify multi[0][0]:
Multi = [[0] * 5] * 3
Multi[0][0] = ' love of the '
Print Multi
The results of the output will be:
[[' Love of the ', 0, 0, 0, 0], [' Love of the ', 0, 0, 0, 0], [' Love ', 0, 0, 0, 0]]
We have modified multi[0][0], but we have changed our multi[1][0],multi[2][0. This is not the result we want.

What if we write this:
Multilist = [[0] * 5 for row in range (3)]
Multilist[0][0] = ' love of the '
Print multilist
Let's see the output:
[[' Love of the ', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Yes, no problem. However, because the method of using * is more likely to cause confusion resulting in bugs, it is recommended that the first method above be used, namely:
!--

Code highlighting produced by Actipro Codehighlighter (freeware)
. CODEHIGHLIGHTER.COM/

--> multilist  =  [[0  for  col   in  range ( 5 )] , for  row , in  range ( 3 )]
Related Article

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.