What Does a Colon Mean in Python when You See Something Like This “new_var = a[i:i + counter]”?

Question
You are not familiar with this example of a colon. It appears to be an assignment of a value to itself. You have seen Python function signatures with colons to explain the data type. You have seen colons to signify an if conditional or a for loop. You are not sure what this line of code does:

new_var = a[i:i + counter]

What does this type of colon syntax mean?

Answer
The colon above is not an assignment; the colon in the syntax in the question above is a slice. It is a slice of a list with a starting value "i" (that is inclusive) and a terminating value "i + counter" (that is exclusive). We recommend putting parentheses around the "i + counter" to make it more clear the order of operations.

Here is how we would code the above:

new_var = a[i:(i + counter)]

Leave a comment

Your email address will not be published. Required fields are marked *