0

I would like to append to a single list within a list, without appending to all the 'sibling' lists at the same time.

Suppose I have an empty list of empty lists in Python, such as the following:

    from math import pi
    test = [[]] * 3
    test
    Out[88]: [[], [], []]

Now suppose I want to append an element only to the first nested list. I would say that selecting the first list, index 0:

    test[0]
    Out[89]: []

and appending to that list as follows:

    test[0].append(pi)

should yield a list that looks as follows:

    [[3.141592653589793], [], []]

However, when printing the result, I get the following:

    test
    Out[91]: [[3.141592653589793], [3.141592653589793], [3.141592653589793]]

Can anyone point out where I am making my mistake?

Thanks in advance.

Sam
  • 305
  • 1
  • 8
  • I'm curious, where did you find/learn that `[[]] * 3` thing? – Aran-Fey Apr 04 '19 at 13:44
  • I don't quite recall, just a logical consequence of list concatenation, I guess? That is, if `[1] + [1] + [1] = [1, 1, 1`], it seems only logical that `[1] * 3 = [1, 1, 1]`, too. – Sam Apr 04 '19 at 13:47
  • Try: `test = [[] for i in range(3)]` newline `test[0].append(pi)` newline `print(test)` – Peter Apr 04 '19 at 13:48
  • The issue is that when you do `[[]] * 3` the nested lists are all the same object in memory. – ame Apr 04 '19 at 13:48
  • I see. People keep making this mistake, and I was wondering who/what was responsible for teaching it to them. – Aran-Fey Apr 04 '19 at 13:49
  • Ah I see. That seems like an easy thing to overlook. – Sam Apr 04 '19 at 13:50

0 Answers0