Python: Please explain "More with 'for'"


#1

According to Codeademy, the correct answer is below.

start_list = [5, 3, 1, 2, 4]
square_list = []---------------------Why is square_list needed? How is it connected to start_list? What does [] do?

for number in start_list:------------Where does “number” come from? How does Python know what it means?
square_list.append(number ** 2)
square_list.sort()

print square_list


#2

because we want to create a new list with all the square numbers of start list

not at the moment, at the moment square_list = [] only defines a new empty list

number is declared within the for loop, python will assign each value (in order) of the list you are looping over to the loop iterator (number).


#3

Thank you. Regarding “number”, I still don’t see how Python knows that it refers to the integers inside of start_list. “Number” isn’t a reserved word, isn’t defined as a variable, and doesn’t follow def in a function. I imagine this will make sense as I learn more about Python.


#4

you define number here:

for number in start_list:

now python will handle assigning values from list to this variable


#5

Thanks, but what makes that line work? It seems to link “number” to the entire start_list = [5, 3, 1, 2, 4]. Where is it declared that “number” is to manipulate [5,3,1,2,4] ?


#6

yes, python will assign each value. Maybe use a visualizer to see each step:

http://www.pythontutor.com/visualize.html#mode=edit

given my explanations aren’t helping.

number is not manipulating the start_list, the values assigned to number are a copy, that is why we create a new list.


#7

A for-statement lets the programmer specify a name and an iterable.
Python then asks the iterable for values and assigns them to that name.
Additionally there is a suite of statements to be executed each iteration.

“what makes it work” is that python code doesn’t run directly on your hardware, there is additional code elsewhere (in python itself and in the iterable) which makes it so. You use a for-statement to leverage that.


#8

Thank you very much for sharing your time and knowledge with me.


#9

Codeacademy asked me to use twenty words in my email to you. Here goes: Thank you very much for sharing your time and knowledge with me.


#10

Codecademy asked me to use twenty words in my email to you. Here goes: Thank you very much for sharing your time and knowledge with me.


#11

Uhm. Well… that’s odd


#12

We’re sorry, but your email message to [“codecademy+955e34edf79143cc57f68bd40cfbf241@discoursemail.com ”] (titled Re: [Codecademy Discuss] [Python/Python Lists and Dictionaries] Python: Please explain “More with ‘for’”) didn’t work.

Reason:

Body is too short (minimum is 20 characters)

If you can correct the problem, please try again.


#13

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