python [:] notation and range

python, syntax

Solution

This is called "slicing". See the tutorial sections on Strings and Lists for a good description of how it works. (In your example, it's actually a `ctypes` array that's being sliced, not a list, but they work the same way. So, for simplicity, let's talk about lists.)

The notation `indexes[:]` is a slice of the entire list. So, you can do this:

a = [1, 2, 3]
b = a[:]

… to get a copy of the whole list, and this:

a[:] = [4, 5, 6]

… to replace the contents of the whole list.

You may wonder how this is different from just using `a` itself. The difference is that in the first case, `b = a` doesn't copy the list, it just makes another reference to the same list, and in the second case, `a = [4, 5, 6]` doesn't mutate the list, it rebinds `a` to refer to a new list. Here's an example that shows the difference:

>>> a = [1, 2, 3]
>>> b = a           # b is now the same list as a
>>> a[0] = 10       # so changing that list is visible to b
>>> b
[10, 2, 3]

>>> a = [1, 2, 3]
>>> b = a[:]        # b is now a new list, with a copy of a
>>> a[0] = 10       # so changing the original list doesn't affect b
>>> b
[1, 2, 3]

>>> a = [1, 2, 3]
>>> b = a           # b is now the same list as a
>>> a = [4, 5]      # but now a is a different list
>>> a[0] = 10
>>> b
[1, 2, 3]

>>> a = [1, 2, 3]
>>> b = a           # b is now the same list as a
>>> a[:] = [4, 5]   # and we've replaced the contents
>>> b
[4, 5]

You may wonder why anyone would use `range(2000, 3000)[:]` on the right side of the assignment.

Well, I wonder the same thing.

If this is Python 2.x, `range(2000, 3000)` is a brand-new list. You replace the contents of `indexes` with the contents of that range list, then give up your only reference to the range list. There is no way anyone could possibly end up sharing it, so there is no good reason to make an extra copy of it, unless you're worried that your computer has too much CPU and too much RAM and might be getting bored.

If this is Python 3.x, `range(2000, 3000)` is a smart range object. And `range(2000, 3000)[:]` is a new and equal range object. The copying this time is a lot cheaper, but it's exactly as unnecessary.

Problem

I've been tasked with converting some python code over to Java. I came across some notation I'm not familiar with and can't seem to find any information on. I'm guessing this is a lack of keywords on my part. I've sanitized the code and hard coded some basic values for simplicity. ``` index_type = c_int * 1000 #size of int, basically 1000 integers? indexes = index_type() # not entirely sure what this does indexes[:] = range(2000, 3000)[:] # no idea # c_int equals 4 ``` The logic doesn't really matter to me, I'm just trying to figure out what's going on in terms of datatypes and converting to Java.

Original source