0

I'm following the book "Learn Python The Hard Way" And I don't understand what is going on in this function in Exercise 39.

def new(num_buckets=256): #So the function is made and its named "new" and the argument inside is
    """Initializes a Map with the given number of buckets."""
    aMap = [] #then it creates an empty list and names it aMap 
    for i in range(0, num_buckets): #This loop is created named i and it is ranging from 0-255.
        aMap.append([]) #then it adds a list inside our aMap variable.
    return aMap

I don't know what the "for i in range(0,num_bucketss) is doing here. What is it doing the append command?

Lia
  • 5
  • 3
  • Add a line `print(i)` and think how aMap changes each time. Also, think about the variable name `num_buckets`... – cphlewis Apr 13 '15 at 21:19
  • I've tried adding a print command. It gives me this though: "" – Lia Apr 13 '15 at 21:23
  • Well, then you're definitely doing *something* wrong -- did you use the exact print statement I suggested? Being able to make looping explicit is helpful while learning. – cphlewis Apr 13 '15 at 22:51

1 Answers1

0

It's adding as many empty lists in aMap as num_buckets specifies. So, if num_buckets = 5, aMap will be a list of 5 empty lists.

As for why it is doing that, we'll need more context.

EDIT:

Seeing the context, it's doing this to create a number of empty buckets for the hashmap. You can read more about how a hashmap uses buckets here: What is meant by number of buckets in the HashMap?

Community
  • 1
  • 1
Ayush
  • 41,754
  • 51
  • 164
  • 239
  • 1
    It's used to create our own dictionary module:http://learnpythonthehardway.org/book/ex39.html . so if it was num_buckets = 3. It's basically making 3 lists inside a list? Like [ [],[],[] ] ? – Lia Apr 13 '15 at 21:15
  • @Lia: Correct, it would make `[[],[],[]]`. Seeing the context, it's doing this because a dictionary operates using a number of `buckets`. See edit for more details. – Ayush Apr 13 '15 at 21:16
  • Ok I have one more question. How is the "for i in range(0, num_buckets): applied to aMap.append([])? I thought since the "for loop" is named "i" that it has to be applied somewhere in aMap.append() to have it create 255 lists, but I'm thinking aMap.append([]) has no relationship to the loop – Lia Apr 13 '15 at 21:19
  • `i` is the loop counter here. There is no requirement that you have to use the counter in the loop. For example: `for i in range(1, 100): print "Hello World!" ` – Ayush Apr 13 '15 at 21:21
  • ahh ok I get it. Thanks for the help. This has been bothering me all day and I couldnt understand why. The book didn't go as in depth with loops as I would have wanted. Your Hello World example was very useful. – Lia Apr 13 '15 at 21:24