More with 'for'


#1

https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/6?curriculum_id=4f89dab3d788890003000096

Hi everyone, My name is Ryan. I've completed this challenge already, I'm just wondering what the best way to code this. In my code you will see the .sort() method inside of the for loop. My question is whether or not the .sort() method should go inside or outside the loop.

My code

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

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

print square_list

Is it better like this?

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

Your code here!

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

square_list.sort()

print square_list


#2

outside the for loop, why sort in each iteration if you can also sort one time at the end? The latter is more effective


#3

Thank you very much. That's exactly what I was thinking, just wanted a second opinion :slight_smile:


#4

@stetim94 actually my question is on the same topic. Can you give me a hint?


#5

its a forum, just be patient please. Yes i will help you, but i can't while i am sleeping


#6