Help with 9


#1

May I know what is the difference between the following 2 codes? Example 1 returns nothing in the preview window while Example 2 returns numbers in the preview window. Both examples pass though (ie. allow you to proceed to the next level)

1) Example 1

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

square_list = []
for numbers in start_list:
    square_list.append(numbers**2)
    
print square_list.sort()

2) Example 2

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

square_list = []
for numbers in start_list:
    square_list.append(numbers**2)
    square_list.sort()
    
print square_list

#2

Hi @wengjunkai ,

Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. This will enable us to see important details, such as the indentation and underscores.

The sort method sorts a list, in place, but does not return the list. So, the attempt to output the list here is unsuccessful ...

print square_list.sort()

Assuming the indentation is correct in your preceding lines of code, this works, because you sort the list, in place, then output it ...

square_list.sort()
print square_list

#3

Hi @appylpye

Thanks for the explanation, I have formatted it. Hope its easier to read.

I have problems understanding what you mean by "The sort method sorts a list, in place, but does not return the list." Would you mind elaborating?

Thanks.


#4

Hi @wengjunkai ,

The following program and its output may help ...

# sort_demo.py
nums = [7, 4, 9, 1, 3, 8, 6, 2, 5]
print nums
print "Let's sort the list."
temp = nums.sort()
print "Let's print the nums list."
print nums
print "Let's print temp, which was assigned the returned value."
print temp

Output ...

[7, 4, 9, 1, 3, 8, 6, 2, 5]
Let's sort the list.
Let's print the nums list.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Let's print temp, which was assigned the returned value.
None
  • First, we create an unsorted list, and assign it to nums.
  • We print it, and of course it is in its original order.
  • Then, we call the sort method on it the list, and assign the returned value to temp.
  • We print the value of nums, and see that the original list has been sorted. This is what we mean when we say that the list has been sorted in place.
  • Now, we print the value of temp, and we see that it is None, because while the sort method sorted the list, it did not return the list.