0

I have a question concerning this piece of code:

def new_field():
    global field
    field= [[]]*9
    for x in range(9):
        for y in range(1,10):
            field[x].append([y," "])
    return field

The way I understand for-loops, it should return a list like this: [[[1, " "], [2, " "], [3, " "], ...[9, " "]], [1, " "], [2, " "], ...

which would mean that field should have a length of 9 for every index from 0 to 8 ->

len(field[0]) should be 9. Instead the length is 81 for every index, what should be the entire list can be found in every sublist.

It looks like this:

[[[1, ' '], [1, ' '], [1, ' '], [1, ' '], [1, ' '], [1, ' '], [1, ' '], [1, ' '], [1, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [2, ' '], [3, ' '], [3, ' '], [3, ' '], [3, ' '], [3, ' '], [3, ' '], .......

Now I have a feeling that I simply dont understand how exactly for-loops work, but I just dont get what I am missing or where the problem in my thoughtprocess is.

Hope someone can help!

user2299050
  • 145
  • 7

2 Answers2

4

The way I understand for-loops ...

Yes, but you misunderstand references.

>>> a = b = []
>>> a.append(1)
>>> b
[1]

You need to create the sublist new each time.

field = [[] for x in range(9)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

Your problem is with this line:

field= [[]]*9

Instead, it needs to be like this:

field= [[] for _ in range(9)]

This is because the current code is creating a list that has 9 copies of the same list.

Below is a demonstration:

>>> x = [[]]*2
>>> x
[[], []]
>>> id(x[0]) == id(x[1]) # The lists have the same id, so they are the same
True
>>> x = [[] for _ in range(2)]
>>> x
[[], []]
>>> id(x[0]) == id(x[1]) # The lists have different ids, so they are different
False
>>>