0

I've been learning Python 3 over the past few weeks. I've run into a snag:

Logically, the line nestedLists[2][4] = "a" should set the 5th member of the 3rd list in this list of lists to "a." Unfortunately, for reasons I don't understand, it sets the 5th member of every list in the list to "a." This is my code:

gameList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

def buildList(gameListt):
    gameListt[0] = ("~ " * 60).split()
    for i in range(len(gameListt)):
        gameListt[i] = gameListt[0]
    return gameListt


gameList = buildList(gameList)

print(gameList)
gameList[2][4] = "a"
print(gameList)

I'm utterly lost here. The syntax checks out fine, and when I try this:

gameList = [["c","a","t"],["h","a","t"]]

gameList[0][2] = "b"
print(gameList)

It works fine, and outputs "cab" and "hat." I need help!

Thanks in advance!

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

1 Answers1

2

gameList starts off being a list of distinct lists, however here:

for i in range(len(gameListt)):
    gameListt[i] = gameListt[0]

You are making each element of gameListt the same list

You should do something like this instead

def buildList(gameListt):
    for i in gameListt:
        i[:] = ["~"] * 60
    return gameListt

Also if you initialise gameList like this:

gameList = [[] for x in range(15)]

It's easier to see it's got 15 sublists

John La Rooy
  • 295,403
  • 53
  • 369
  • 502