Is list declaration necessary?


I have removed the line square_list=[]

start_list = [5, 3, 1, 2, 4]
for x in start_list:
print square_list

The output looks like this
[1, 1, 4, 4, 9, 9, 16, 16, 25, 25]

Can someone please explain why the output is like this?


The output is,

Because you have raised all numbers in the list by a power of 2


The output with square_list=[] is [1,4,9,16,25]

But without that the numbers seem to be squared twice, as in ,the output is
[1, 1, 4, 4, 9, 9, 16, 16, 25, 25]

I want to know what difference square_list=[] is making..


Hi @krr126 krr ,

It is important to format code when you post it. That enables users to see your indentation and other important details.

See How do I format code in my posts?.

This statement is necessary ...


... because it defines the square_list variable and assigns an empty list to it.

If the variable, square_list, has not been defined, your code will raise an error when it attempts to access it.

If your for loop executes with square_list already having values in it prior to its execution, those items will be there in addition to the items that are appended to the list within the loop.

What happened to produce the result that you reported is that the first time you ran your code, the statement referred to above assigned an empty list to the variable. Then, all the squares got appended to the list as the loop executed. Up until then, everything was fine.

But then you removed the statement and executed your code again. Due to the manner in which Codecademy manages memory, square_list was still in memory from the previous run, and the squares got appended to it again. The result was that you had two copies of each square in the list.

Restore the statement, and submit your code again.


As an aside,

The only time we do not need to declare an empty list is if we are assigning a list comprehension. If this subject has not come up yet, it will soon.

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

squares_list = sorted( [ x ** 2 for x in start_list ] )

print (squares_list)    # [1, 4, 9, 16, 25]


Thank you @appylpye and @mtf for the explanation. It makes much more sense now:)


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