9. More with for


#1

Quick question, I removed the .sort() function after completing the section and my code looks like this:

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

# Your code here!
for x in start_list:
  square_list.append(start_list[x-1] ** 2)

#square_list.sort()
print square_list

And the output comes out as [16, 1, 25, 9, 4]. If I understand correctly .append() adds to the end of the list, shouldn’t this output be [25, 9, 1, 4, 16]. Is there something I’m missing?


#2

To get the result you expect, work on the look up value, directly:

square_list.append(x ** 2)

Now the order will match the initial list. What your code is doing is using the values in the list, minus 1 as indexes, hence,

    index[5-1] => 4 => 16    // start_list[4] value is 4.
    index[3-1] => 1 => 1
    index[1-1] => 5 => 25
    index[2-1] => 3 => 9
    index[4-1] => 2 => 4

#3

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