0

I am trying to solve leetcode problem 6 and encountered something that I can't understand. The problem is asking me to use a zigzag pattern to rearrange a string column by column and output it row by row. In my function I used two different ways to create my initial list that stores the output. However, one of them works and the other doesn't. Can someone help me understand why this is happening? Here are the methods I used to initilize the list down below. Since there are multiple rows to output and I want to keep track of which row contains what letter, I thought I could create a list includes muliple sublists.The first method worked just fine, however, the second one could not distinguish which sublist contains which letter and appened the entire string after iterations.

zigzag = [[] for x in range(n)]
zigzag = [[]]*n


for crct in l:
   zigzag[row].append(crct)

Here's the output for the first method: [['P', 'I', 'N'], ['A', 'L', 'S', 'I', 'G'], ['Y', 'A', 'H', 'R'], ['P', 'I']]

And the output for the second: [['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G'], ['P', 'A', 'Y', 'P', 'A', 'L', 'I', 'S', 'H', 'I', 'R', 'I', 'N', 'G']]

Yihan Chen
  • 41
  • 6
  • 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) – kaya3 Feb 20 '20 at 17:11

1 Answers1

0

When you are doing, zigzag = [[] for x in range(n)], python created n different instances of list. So when you are performing append operation it works as expected.

But in case of zigzag = [[]]*n, python created only one instance and after that you are asking python to create n copies of that and which is the reason every index of the outer list contains the exact same elements as they are pointing to the same reference.


For more clarification, check the output of the below code snippet.

zigzag = [[]]*5
print([id(i) for i in zigzag])
Output: [4606230920, 4606230920, 4606230920, 4606230920, 4606230920] # Same address

zigzag = [[] for x in range(5)]
print([id(i) for i in zigzag])
Output: [4606232136, 4606183048, 4606167304, 4606231240, 4606230792] # Different addresses
GreatWhite
  • 106
  • 5