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
10 ответов
+ 7
x**2 is x raised to the power 2. x*2 is x multiplied by 2.
+ 5
The "return" is only used inside a function
+ 5
print([x * 2 for x in my_list])
+ 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
+ 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)
0
Run your could, you ll see, return outside function error.
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?
0
In the first code replace return with print
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