More questions for "More with 'for'"

#1

I completed the exercise, but later I also wanted to `.sort()` the `start_list`. Then, I noticed that if I `.sort()` the `start_list` within the loop block, the printed `square_list` gives me a different result than when I `.sort()` the `start_list` outside of the loop block, and I can't understand why. Any thoughts?

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

for number in start_list:
square_list.append(number ** 2)
square_list.sort()
start_list.sort()

print start_list
print square_list

#this prints:
#[1, 2, 3, 4, 5]
#[4, 9, 16, 25, 25]
#None"``````

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

for number in start_list:
square_list.append(number ** 2)
square_list.sort()

start_list.sort()

print start_list
print square_list
#prints:
#[1, 2, 3, 4, 5]
#[1, 4, 9, 16, 25] (different numbers)
#None``````

Thank you!

More with 'for'
#2

when sorting inside the loop, use sort before append if you want to yield the same result

the problem is that when sorting inside the loop, in the first iteration, you append `5` to square_list, then you sort the list, then the order becomes different, then you append the rest of the list (2,3,4,5 given the list is now sorted)

in essence, 5 is appended twice, where 1 is skipped (because of when you sort)

you can add print statements to confirm this

#3

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