More with 'For'


#1

so here's my code:
start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:
n = number
start_list.append(n ** 2)

start_list.sort()

print square_list

this is the message that pops up:
The program took too long to finish. Check your code for infinite loops and try again.

So I was wondering if someone could explain it to me.


#2

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

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

square_list.sort()

print square_list.sort()

I looked at some other posts and rewote, I got it :grin:


#3

thank you but you what does the .append actually do here?

I was able understand most of it but if anyone can simply this exercise I
would greatly appreciate.


#4

Is the .sort() needed when you print? I thought sort didn't actually have to be included when printing a code.


#5

Hi All,

My code is below. I'm also a newbie but I believe its not necessary to do this "n = number", as you are already storing the value in "number". So I did this "square_list.append(number ** 2)"
Which appends the square of "number" to square_list. Run my code below and you will see the list been built up on each pass of the for loop and then you will finally see what the sort does.

Also note I don't have "square_list.sort()" in the for loop. Again I think its bad coding, perhaps, to sort on every pass of the for loop. So I just sort it after "square_list" is fully populated.

My two cents!!

pyted15

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

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

square_list.sort()
print square_list