0

Why won't this simple python script work

I want to simply multiply everything in a list by 2, but I don't want to use lambdas or anything. My_list = [1,2,3,4,5] for x in my_list: return (x**2) Print (x) Firstly, why is it incorrect to use "return" there? I know a way to do it is like this: My_list = [1,2,3,4,5] for x in my_list: new_list= [] new_list.append (x**2) Print (new_list) In wondering why I didn't need to use return and why I'd use the x**2 after the append instead of before? Thanks in advance

5th May 2020, 10:19 PM
Andrew Chadwick
Andrew Chadwick - avatar
10 ответов
+ 7
x**2 is x raised to the power 2. x*2 is x multiplied by 2.
6th May 2020, 1:17 AM
David Ashton
David Ashton - avatar
+ 5
The "return" is only used inside a function
5th May 2020, 10:23 PM
Lord Nader
Lord Nader - avatar
+ 5
print([x * 2 for x in my_list])
6th May 2020, 1:19 AM
David Ashton
David Ashton - avatar
+ 1
That new list should be declared empty outside for Loop and you are calling a list method append and then passing it some arguments ,and so you can't use x**2 before
5th May 2020, 10:27 PM
Abhay
Abhay - avatar
+ 1
There are four problem in your second code: 1- new_list = [] should be defined before for loop 2-print()shold be placed outside of for loop and after that. 3-print() Not Print() 4-My_list Not my_list My_list =[1, 2, 3, 4, 5] new_list = [] for x in My_list: new_list.append(x**2) print(new_list)
6th May 2020, 2:03 AM
hassan
0
Run your could, you ll see, return outside function error.
5th May 2020, 10:42 PM
S.K
0
Ah thanks everyone. Ignore the capitalisation, I'm just lazy when typing on my phone. It's not actually like that in my code. Lord ken what did you mean sorry?
6th May 2020, 6:44 AM
Andrew Chadwick
Andrew Chadwick - avatar
0
In the first code replace return with print
7th May 2020, 8:44 AM
Pratham Chugh
0
Also return can only be used in a function. You are using ** instead of *. A ** refers to raise to the power of exponentiate. Whereas * refers to multiply
7th May 2020, 8:45 AM
Pratham Chugh