Python and list dictionaries - 9. More with for


#1

Hi, I’ve tried using .sort() but getting a “None” result. Although I was enabled to continue I want to know why my code returns “None” instead the list of ordered numbers:

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

# Your code here!

for i in start_list :
  square_list.append(i ** 2)

square_list = square_list.sort()
print square_list

Also tried with:

print square_list.sort()

Both things gave output:

None

Update: It only worked like this:

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

# Your code here!
start_list.sort()

for i in start_list :
  square_list.append(i ** 2)

print square_list

Or like this:

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

# Your code here!

for i in start_list :
  square_list.append(i ** 2)

square_list.sort()

print square_list

Output:

[1, 4, 9, 16, 25]

Why I cant reassign the list or print using .sort()?

square_list = square_list.sort()
print square_list.sort()

#2

because .sort() manipulates the list, if you want to re-assign you could do:

start_list = [5, 3, 1, 2, 4]
x = sorted(start_list)

print start_list, x

but now we have two lists, so this is clearly less efficient.


#3

Interesting, thanks!!


#4

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