Python's two-dimensional array operation

Source: Internet
Author: User
Tags shallow copy

You need to use a two-dimensional array in your program to find such a usage on the Web:

123456 #创建一个宽度为3,高度为4的数组#[[0,0,0], # [0,0,0],# [0,0,0],# [0,0,0]]myList =[[0] * 3] *4

But when operation mylist[0][1] = 1 o'clock, the entire second column is found to be assigned, which becomes

[[0,1,0],

[0,1,0],

[0,1,0],

[0,1,0]]

Why... The Python standard Library found the answer in the back.

List * N->n shallow copies of list concatenated, n a shallow copy of List of connections

Cases:

123456 >>> lists =[[]] *3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]]

[[]] is a list containing an empty list element, so [[]]*3 represents 3 references to this empty list element and modifies any

An element will change the entire list:

So you need to create a multidimensional array in a different way to avoid shallow copying:

123456 >>> lists =[[] fori inrange(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]]

The previous two-dimensional array was created in the following way:

1 myList =[([0] * 3) for i inrange(4)]

Python's two-dimensional array operation

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.