What is the colon in this code doing?

def print_board(self):
        for row in [self.board[i*3:(i+1) * 3] for i in range(3)]:
            print('| ' + ' | '.join(row) + ' |')

Can anyone explain this? It’s from FreeCodeCamps video tutorial. I have no idea what the colon dose in this part of the code [i*3:(i+1) * 3]


Basically selecting the items in the list ‘board’ that have indexes equal to the values in the range:

[i*3,(i+1)*3[ <==> from i*3 to (but not including) (i+1)*3

Also similar functionality to array.splice() in javascript.

The use of the colon is the main thing that I do not understand here. When I look up Python colon, I get no answer. Does it work like an equal sign here? dose it end a line of code? Dose it just separate the two parts of Code? I do not know JavaScript.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

The previous poster was trying to explain the colon to you without using a colon since it was confusing you I guess.

The colon is part of python’s slice index notation.

Here’s an article that explains how to use it (in short the number on the left of the colon is where the slicing begins and the number on the right is where it ends)

Thanks, slicing. That is all I needed to know. I have already studied slicing.

1 Like

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