Python Initializes a multidimensional array of code

Source: Internet
Author: User
The best way to initialize a 5 x 3 array of 0 per item in Python is:
multilist = [[0 for Col inch Range ( 5 )] for Row inch Range ( 3 )]
We know that in order to initialize a one-dimensional array, we can do this:
alist = [0] * 5
Yes, if 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 modified multi[0][0]:
Multi = [[0] * 5 ] * 3
Multi[0][0] = ' Love China '
Print MultiThe result of the output will be:
[' Love China ', 0, 0, 0, 0], [' Love China ', 0, 0, 0, 0], [' Love China ', 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.

If we write like this:
multilist = [[0] * 5 for Row inch Range ( 3 )]
Multilist[0][0] = ' Love China '
Print multilistWe look at the output:
[' Love China ', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Yes, no problem. However, it is recommended to use the first method above, since the use of the * method is more likely to cause confusion than the bug, that is:
multilist = [[0 for Col inch Range ( 5 )] for Row inch Range ( 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.