0
n = int(input("Enter the number: "))
startRow = 0
endRow = n - 1
startColumn = 0
endColumn = n - 1
k = 1

matrix = [[0]*n]*n

i = startColumn
while(i <= endColumn):
    matrix[startRow][i] = k
    k = k + 1
    i += 1
matrix[0][1] = 6

print(matrix)

output

python print_patterns.py 
Enter the number: 5
[[1, 6, 3, 4, 5], [1, 6, 3, 4, 5], [1, 6, 3, 4, 5], [1, 6, 3, 4, 5], [1, 6, 3, 4, 5]]

Q1. I am unable to understand why second element in every array is 6?

Q2. In the first while loop I have assigned values only to first array elements but still it allocated all the rows with same data?

  • firstly change `matrix = [[0]*n for i in range(n)]` and read about `shallow copy and deep copy` from https://www.python-course.eu/python3_deep_copy.php – Epsi95 Sep 12 '21 at 14:38
  • 4
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Hampus Larsson Sep 12 '21 at 14:39
  • Thank you Esi95 and Hampus Larsson – Lalit Bhardwaj Sep 14 '21 at 16:20

1 Answers1

0

In your method, Python doesn’t create 5 integer lists but creates only one integer list and all the indices of the list matrix point to the same int list.

Using 2D lists the right way

Visit this link for more information.

KavG
  • 169
  • 1
  • 12