0

The code is given below.

board = []

yes = 0

board.extend('-' * 9)

for index, i in enumerate(board):

   if index % 4 == 0 and yes < 3:
      board.insert(index-1 ,'\n')
      yes += 1

print(board)

This code gives a input like: ['-', '-', '-', '\n', '-', '-', '-', '\n', '-', '-', '\n', '-']

I cant understand why the third '\n' is coming.

  • 2
    Don't change `board` while iterating it – DeepSpace Jul 12 '21 at 09:50
  • Modifying an object while you're iterating it makes things complicated (though it can be done). For the sake of getting-things-done w/o pulling your hair out, you should consider to build a new list instead. – Mike Scotty Jul 12 '21 at 09:51
  • The simplest way will be to use [`join`](https://docs.python.org/3/library/stdtypes.html#str.join): `board = '\n'.join(['-'*3] * 3)` – Tomerikoo Jul 12 '21 at 10:01

2 Answers2

0

It happend when you check index % 4 == 0, index=0 also fits this condition.

index % 4 == 0

0 % 4 == 0 - True.

Then you use index - 1 in insert and get index = -1. If you try to use this code that I wrote below, you get your problem

board = []
board.extend('-' * 9)

board.insert(-1, '\n')
print(board)


Output: ['-', '-', '-', '-', '-', '-', '-', '-', '\n', '-']
magicarm22
  • 135
  • 10
  • 2
    The quickest fix is to just use `for index, i in enumerate(board[1:], 1):`, which eliminates dealing with `index == 0` without needing to check it in every iteration – DeepSpace Jul 12 '21 at 09:52
0

You could do something like this:

enumerate has a start parameter which you can use

board = []

yes = 0

board.extend('-' * 9)

for index, i in enumerate(board,start=1):

   if index % 4 == 0:
      board.insert(index-1 ,'\n')

print(board)
  • Be careful, if `i` will ever be used in the loop then there will be a mismatch between the index and the value of `i`. Either signify it is not being used by renaming it to `_`, use `board[1:]` or just use `for index in range(1, len(board))` although the latter is considered to be less idiomatic – DeepSpace Jul 12 '21 at 12:12