0

Let's say I create a list containing empty lists:

ex_list = [[], [], [], [], []]

How do I append elements to the specific empty lists contained in ex_list?

For example, I would expect that:

ex_list[0].append("a")

would return:

ex_list = [[a], [], [], [], []]

But it returns:

[['a'], ['a'], ['a'], ['a'], ['a']]
mdml
  • 22,442
  • 8
  • 58
  • 66
David
  • 1
  • 4
    Are you sure that's how you're initializing `ex_list`? The example you show works as you expected for me. – mdml Jun 13 '14 at 19:58
  • [Works on my machine](http://ideone.com/hOtJF4). – Kevin Jun 13 '14 at 19:59
  • `>>> ex_list = [[], [], [], [], []] >>> ex_list[0].append(1) >>> ex_list [[1], [], [], [], []]` – agamike Jun 13 '14 at 20:00
  • Are you sure you didn't do `ex_list = [[]]*4`? – g.d.d.c Jun 13 '14 at 20:00
  • He obviously did not initialize the list like that. And this have been answered countless times before – M4rtini Jun 13 '14 at 20:01
  • You need to use deep copy: https://docs.python.org/2/library/copy.html#copy.deepcopy – Jason Nance Jun 13 '14 at 20:01
  • @JanVlcinsky either the asker wrote the code they said they wrote, in which case the outcome is as expected and there is no problem to solve, or they wrote the code described in the duplicate and they can find their answer there. – murgatroid99 Jun 13 '14 at 20:06
  • @murgatroid99 You are right. senderle have seen a bit deeper then me, and his decision to mark it as duplicate was good one. – Jan Vlcinsky Jun 13 '14 at 20:08

0 Answers0