What does [:] mean in Python?
A short explanation, since it took me a long time to figure it out.
When I read through this code, the [:] caught me off guard.
I’m normally a JavaScript guy, so I’m aware of the typical usage of square brackets for indices in an array. I was also familiar with slicing strings with a range in Python, such as:
str = “this is a string”
print( str[0:4] ) # outputs 'this'
So when I saw the [:], my first reaction was that it must be slicing everything. And in a way, that’s exactly what it’s doing.
The [:] makes a shallow copy of the array, hence allowing you to modify your copy without damaging the original.
The reason this also works for strings is that in Python, Strings are arrays of bytes representing Unicode characters.
The officially supported method of doing this is the copy function, as demonstrated here. However, we as programmers like to take the easy way out, which in this case is [:].
Even if you are not one of those programmers, chances are you’ll see some code written by one, so now it will make more sense.
I know this was a short read, but I hope it helped deepen your understanding of Python. Knowledge is power!