Search⌘ K

A Tic-tac-toe Where X Wins in the First Attempt!

Understand how Python handles list references and mutability through a tic-tac-toe example where the same list is referenced multiple times. Learn why modifying one element affects others and discover how to avoid these issues using list comprehension. This lesson helps you grasp important Python data handling concepts and prevent common coding mistakes.

We'll cover the following...

Who doesn’t like to win tic-tac-toe? But what happens if the game is biased against you? Let’s learn to level the playing field.

Python 3.5
empty_cell = ""
# Let's initialize a row
row = [empty_cell] * 3 #row i['', '', '']
# Let's make a board
board = [row] * 3
print(board)
print(board[0])
print(board[0][0])
board[0][0] = "X"
print(board)

We didn’t assign three "X"s, did we?

Explanation

When we initialize the row variable, this visualization explains what happens in the memory

And when the board is initialized by ...