Difference Between Generating List with Loops and generating list with a single line statement


#1

Suppose I want a 5x5 grid size list.
So if we want to use loops, then we can do this in this way

board = []

for i in range(0, 5):
  board.append(['O'] * 5)
print board

And if we want to generate same list without using loops, then we can do it as follows

board = ([['O'] * 5]) * 5
print board

So, the question is, what’s the difference between the two results. I know the results would be same, but in Codecademy Editor, it says,

It looks like your board has 5 references to the same row! This will cause problems later on. Read the hint for more information and use a for loop to complete this lesson

#2

they are not the same, python is saving memory when you do ([['O'] * 5]) * 5 by using the same list 5 times.

If you give 5 of your friends your address of your house, the address refers to the same house. This is what python has done with the lists. It created a list (house), and handed out 5 addresses (memory addresses in this case).

Later in this program, we want to mark incorrect guesses by the user with an X, lets attempt this now to see the problem with your code:

board = ([['O'] * 5]) * 5
board[0][0] = "X"
print board

see how all 5 lists are updated? While if you use the loop to create 5 separate lists, only a single list would update:

board = []

for i in range(0, 5):
  board.append(['O'] * 5)
board[0][0] = "X"
print board

so although the codes look similar, they are not behaving the same.

This fits with my houses analogy, if you make a change to your house (paint the door for example) and your friends would come and visit (reading the list like print board does) they would all notice the change.


#3

Not…saving memory. That’s straight up what the code says to do

(and besides, how would python know how to copy something, it’s a pretty good assumption that it doesn’t ever happen)


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.