0

What is different about these two methods of initializing that changes the answer so drastically?

queries = ["1 0 5",
"1 1 7",
"1 0 3",
"2 1 0",
"2 1 1"];
#Option 1:
queries_num = [[]]*len(queries);
#Option 2:
queries_num = [[],[],[],[],[]];
for x in queries:
    for y in x:
        if y in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            queries_num[queries.index(x)].append(int(y));
print(queries_num)

Option 1 prints:

[[1, 0, 5, 1, 1, 7, 1, 0, 3, 2, 1, 0, 2, 1, 1], [1, 0, 5, 1, 1, 7, 1, 0, 3, 2, 1, 0, 2, 1, 1], [1, 0, 5, 1, 1, 7, 1, 0, 3, 2, 1, 0, 2, 1, 1], [1, 0, 5, 1, 1, 7, 1, 0, 3, 2, 1, 0, 2, 1, 1], [1, 0, 5, 1, 1, 7, 1, 0, 3, 2, 1, 0, 2, 1, 1]]

Option 2 prints:

[[1, 0, 5], [1, 1, 7], [1, 0, 3], [2, 1, 0], [2, 1, 1]]

I'd like to use Option 1 but get the answer that Option 2 gives.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Use `[[] for _ in len(queries)]` – Barmar Mar 03 '22 at 17:19
  • Hi thanks for answering my question so quickly! I just came upon this myself. What is the difference between [[] for _ in len(queries)] and [[]] * len(queries)? – William Chandler Mar 03 '22 at 17:30
  • One is creating a new list each time, the other is making multiple references to the same list. I gave you a link to a question that explains this, did you read it? – Barmar Mar 03 '22 at 17:31
  • Just read it now and that explains it. Thank you so much! I hope you know how much people appreciate people like you who take time out of their day to help others. I hope you have a wonderful rest of your day! Thanks again. – William Chandler Mar 03 '22 at 17:34

0 Answers0