By Charles Anderson


2008-10-27 14:57:22 8 Comments

I needed to create a list of lists in Python, so I typed the following:

myList = [[1] * 4] * 3

The list looked like this:

[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]  

Then I changed one of the innermost values:

myList[0][0] = 5

Now my list looks like this:

[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]  

which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray
  • 3084729 View
  • 3233 Score
  • 27 Answer
  • Tags:   python list

42 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

44 Answered Questions

31 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 4084667 View
  • 3324 Score
  • 31 Answer
  • Tags:   python list indexing

22 Answered Questions

20 Answered Questions

[SOLVED] How to Sort a List<T> by a property in the object

27 Answered Questions

[SOLVED] Why not inherit from List<T>?

10 Answered Questions

[SOLVED] Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

Sponsored Content