9.More with 'for' (Weird answer)


#1
start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for number in start_list:
  print square_list.append(number ** 2)
  square_list.sort()


print square_list

gives the answer

None
None
None
None
None
[1, 4, 9, 16, 25]

why is that. I’ve checked the automated solution and looks exactly the same as my code but without all the none prints.


#2

why do you have a print statement when appending? appending modifies the list and returns None. By putting a print statement while appending, you get None printed

why would you want to sort each iteration of the loop? Why not once at the end?


#3

Ahh I see my mistake, I thought it worked like:

Square_list getting appended with all numbers all at once and then printed onto the screen, but I guess thats not it.

So apparently it repeats the little block as many times as there are items in the list? Which is why I also see its stupid to sort it within the block.
Though I would have thought it would return and print each append I make for each loop but comes back as none. Guess I’m not sure why that is still.


#4

yes, the for loop will loop over all the values in the list.

While every function and method might not have an explicit return it will have an implicit one, that is None

so someone wrote the .append() method, and didn’t explicitly used return, so the implicit one (None) is used by the append method.


#5

Ahh yes got it thanks.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.