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?

3
  • Add a line print(i) and think how aMap changes each time. Also, think about the variable name num_buckets... Commented Apr 13, 2015 at 21:19
  • I've tried adding a print command. It gives me this though: "<function new at 0x01DB6870>" Commented Apr 13, 2015 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. Commented Apr 13, 2015 at 22:51

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

5 Comments

It's used to create our own dictionary module:learnpythonthehardway.org/book/ex39.html . so if it was num_buckets = 3. It's basically making 3 lists inside a list? Like [ [],[],[] ] ?
@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.
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
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!"
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.