#9 More with 'for'


I need help. this is my code.

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

Your code here!

start_list(square_list ** 2).append()

It says:

Oops, try again. Your code looks a bit off. Check the Hint if you need help! Your code threw the following error: unsupported operand type(s) for ** or pow(): 'list' and 'int'




start_list is not a function, but a list, as is square_list. The above is throwing an error since we cannot square a list.

We need to iterate over start_list, and apply the math expression to the individual elements, which results are appended to the square_list.

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

We will now be able to iterate over square_list to print out the new values: Here is a complete example (not meant as solution)

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

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

for x in square_list:
    print x



Study up on for loops to get grounded in this construct. It will be used a lot as you continue to learn so you should be completely comfortable with it. Don't move on until you have done some more reading.

SERP: Python for

As you progress you will discover some very interesting tools that Python offers us to work on problems similar to the one in this lesson. Ignore the following for now. It will come up later.

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

# yet to learn, `lambda` & 'map()`
square_list = map(lambda x: x ** 2, start_list)

# yet to learn, `tuple` and 'zip()`
zipped = [(x, y) for x,y in zip(start_list,square_list)]  

for x in zipped:
    print x


(5, 25)
(3, 9)
(1, 1)
(2, 4)
(4, 16)