The operation method of two-dimensional arrays in Python

Source: Internet
Author: User
Tags arrays shallow copy

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

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.