0
Whats wrong with this code it gives error My_list = [1,2,3,4,5] Number=0 for Number in My_list: My_list = My_list(Number**2) Print My_list
16 Answers
+ 5
Maybe you want listing the square of numbers in the array?
If that's:
My_list = [1,2,3,4,5]
for Number in My_list:
Number=Number**2
print(My_list)
Or:
My_list = [1,2,3,4,5]
for index in range(len(My_list)):
My_list[index] = My_list[index]**2
print(My_list)
WARNINGS:
- "Print" and "print" doesn't are the same... so the "print" only work ( but you can define a custom function named "Print" )
- become accustomed to use parenthesis with print, because in Python 3.x they are required ( and accepted in previous versions, even not required )
[ EDIT ]
Only the second solution work as expected ( in the first, we do operate on value copy, so the array isn't modified ^^ )
+ 4
you need to use index to access to your array.
Things like this :
" My_list = My_list(Number**2)"
are not posible.
+ 3
Ok :)
Well so, my supposition of application of power of 2 for each item was right :P and the soluce previously posted ;)
+ 3
Almost in fact: only the second solution is working... after little edit ( forgot **2 )
+ 3
Yes, probably :P
( I've edited the post with the solution, with explanation on why the first doesn't work )
+ 2
It's quiet not surprising than the Python interpretor fails, because an human itself will have difficulty to understand what this code is supposed to do :P
So what is the behaviour expected ?
+ 2
YuHai says : "what output do you suppose to be?"
Biswascoder finally answers: O/p : [2,81,9,64,25,49]
But still problems:
- your input count 5 elements and your output 6: is that right?
- what's the f**king mathematical relation between input and output?
+ 2
7 ???
in your initial ( input ) list?
So, like this:
My_list = [1,2,3,4,5,7]
?
And what about the mathematical operation(s) you search to obtain ?
+ 2
No, I mean the index of the array.
array[n]
n is the index.
+ 2
Use this
my_list = [1,2,3,4,5]
new_list = [x**2 for x in my_list]
List comprehension is a very powerful technique in Python
+ 1
isnt the output supposed to be [1,4,9,16,25,49]
not [2,4,9,16,25,49]
0
So should i add
Number = Number+1
0
O/p : [2,81,9,64,25,49]
0
what output do you suppose initially?
0
Sorry visph i forgot to add 7 in my list
0
Actully i am still working on it on my laptop there i am using different items
So let me clear
I/p : [1,2,3,4,5,7]
O/p : [2,4,9,16,25,49]