The operation method of two-dimensional arrays in Python

Source: Internet
Author: User
Tags arrays shallow copy in python

This article mainly introduces some Python two-dimensional array operation method, is the basic knowledge of Python learning, need friends can refer to the

You need to use a two-dimensional array in your program, and find one on the web that uses:

?

1 2 3 4 5 6 #创建一个宽度为3, array of height 4 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,0,0]] myList = [[0] * 3] * 4

But when the operation mylist[0][1] = 1 o'clock, it is found that the entire second column is assigned, and becomes

?

1 2 3 4 5 6 7 [[0,1,0], [0,1,0], [0,1,0], [0,1,0]]

Why... I don't understand, back to the Python Standard Library to find the answer

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

Cases:

?

1 2 3 4 5 6 >>> 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, modifying any

An element changes the entire list:

So you need to create multidimensional arrays in a different way to avoid shallow copies:

?

1 2 3 4 5 6 >>> lists = [[] for I in range (3)] >>> lists[0].append (3) >>> Lists[1].append (5) >>> L Ists[2].append (7) >>> lists [[3], [5], [7]]

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

?

1 myList = [ ([0] * 3) for I in range (4)]
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.