#9 More with 'for'


#1

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'

PLEASE HELP!!!


#2

https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/1/6

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

Output

25
9
1
4
16

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

Output

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

#6