Understanding Multiplying One-Dimensional Lists When Creating Empty Multiple Lists in Python 3

Asked 2 years ago, Updated 2 years ago, 240 views

I'm confused about how to create a python3 two-dimensional array list.

 a=[0]*3 for i in range(4)]
b = [[0]*3]*4

for i in range (4):
  for jin range(3):
    a[i][j]=f'{i}_{j}'
    b[i][j]=f'{i}_{j}'

Due to the difference in the way two-dimensional array is created, the results will be different as follows:

For list inclusion of a,

[['0_0', '0_1', '0_2',] , 
 ['1_0', '1_1', '1_2'], 
 ['2_0', '2_1', '2_2'],
 ['3_0', '3_1', '3_2']]

Multiply the list of b by

 [['3_0', '3_1', '3_2',] , 
 ['3_0', '3_1', '3_2'], 
 ['3_0', '3_1', '3_2'], 
 ['3_0', '3_1', '3_2']]

How do I understand the difference in output?

python python3

2022-09-30 22:04

1 Answers

a is another list and b is the same (as metropolis, payaneco wrote in the comments).

The figure below shows for easy visibility.

a is another list, b is the same list


2022-09-30 22:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.