2

I copied this code from this website, and am just wondering about the grammar here? Why is the for loop under the 'i+1'?

# centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}

The code produce the following results:

>>> np.random.seed(200)
>>> k = 3
>>> # centroids[i] = [x, y]
... centroids = {
...     i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
...     for i in range(k)
... }
>>>     
... 
>>> centroids
{1: [26, 16], 2: [68, 42], 3: [55, 76]}
3
  • Irrelevant critique of the code you did not write: would be more efficient to make the i+1 just i and change the range to range(1, k+1). Commented Nov 18, 2017 at 4:02
  • @JohnB Thanks! Why is this the case? Commented Nov 18, 2017 at 16:39
  • 1
    Because the way it is now, an extra addition i+1 is made in each iteration of the loop where only a single addition operation is needed to adjust the range so that it yields the target keys for the dict. If only one argument is provided to range, the start of the range defaults to 0. So essentially, since there is no start or step argument to range, all the i+1 code is doing is keying each integer in the range to be the next iteration's i value (and k in final iteration where i is k - 1). See range for more info. Commented Nov 18, 2017 at 16:52

1 Answer 1

4

It's a dictionary comprehension (similar to a list comprehension), but the brackets make it seem like it's a normal dictionary initialisation.

Imagine if the brackets were on the same line:

centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}

So it's just a more verbose way of saying:

centroids = {}
for i in range(k):
    centroids[i+1] = [np.random.randint(0, 80), np.random.randint(0, 80)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.