0

I wish to expend different elements to a 2D list. the source code is as follows:

import random
import string

batch_size = 3
all_tokens = [[]] * batch_size


for batch_idx in range(batch_size):

    all_tokens[batch_idx].extend([batch_idx+1])


for batch_idx in range(batch_size):

    all_tokens[batch_idx].extend([batch_idx+1] * (batch_idx+1))

print (all_tokens)

I expect the result to be:

[[1, 1], [2, 2, 2], [3, 3, 3, 3]]

However, the actually result becomes:

[[1, 2, 3, 1, 2, 2, 3, 3, 3], [1, 2, 3, 1, 2, 2, 3, 3, 3], [1, 2, 3, 1, 2, 2, 3, 3, 3]]

Does any one can help? thanks a lot

markli
  • 1
  • 1
  • 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) – Paul M. Nov 21 '22 at 16:53

0 Answers0