-4

In my intro computer science class we just finished writing a program to create a tic tac toe board and the way I made my game board was like this;

game_board = [[', ', '], [', ', '],[', ', ']]

I viewed similar problems on the internet and saw another way it was written like this

different_board = [[' '] * 3 for row in range(3)]

I was wondering how the second one would look compared to the first one if it were written out, would they be the same or would it look different?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
lbj1931
  • 1
  • 1
  • I think actually this one is not really a duplicate, since it does use `for row in range(3)` on the outer comprehension, which avoids the problem in that question. – kaya3 Nov 28 '19 at 03:33
  • 3
    That first code sample is syntactically invalid (your quotes and brackets aren't paired properly). We can't compare garbage to valid code. – ShadowRanger Nov 28 '19 at 03:34
  • The first of these lists is a syntax error, though - I'm guessing you copied the code incorrectly. If each of them is supposed to be a list with three spaces in, then both versions have the same result. – kaya3 Nov 28 '19 at 03:34
  • 2
    Either we're looking at a trick question, or there's a typo in the first expression and you need to double up on those quotes. – Grismar Nov 28 '19 at 03:34
  • @eyllanesc: Nothing about this has anything to do with that question; the structure of the second block is explicitly designed to avoid that problem. – ShadowRanger Nov 28 '19 at 03:35
  • 1
    In any event, this is Python. Run both bits of code in an interactive interpreter. `print` it out. You'll have your answer on what it "looks like" (note that `[[' '] * 3] * 3` would also "look the same", but [it would be broken](https://stackoverflow.com/q/240178/364696), so never use that construct). – ShadowRanger Nov 28 '19 at 03:40
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Arkistarvh Kltzuonstev Dec 01 '19 at 10:57

1 Answers1

2

You can just ask Python:

a = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
b = [[' '] * 3 for row in range(3)]
print(a == b)

Result:

True

Also, beware:

c = c = [[' '] * 3] * 3
d = [[' ' for _ in range(3)] for _ in range(3)]
print(a == c)
print(a == d)

They appear the same, but they are only similar - try modifying c and you'll see why:

c[0][1] = 'x'
print(c)

Result:

[[' ', 'x', ' '], [' ', 'x', ' '], [' ', 'x', ' ']]

It's three references to the same list! The definition of d is correct, but it's not immediately clear to most programmers why * 3 has that problem and for _ in range(3) would not, so I'd stay away from these "efficient" definitions.

And you could see what it looks like yourself:

print(b)

Result:

[[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
Grismar
  • 27,561
  • 4
  • 31
  • 54