import math
def ListSqrRoot(nums):
n=len(nums)
for i in range(n):
nums[i]=math.sqrt(nums[i])
def main():
nums=eval(input("Please enter a list of numbers:"))
print( "Before calling the function your list is:")
print (nums)
ListSqrRoot(nums)
print ("After calling the function your list is:")
print (nums)
main()
Asked
Active
Viewed 223 times
0

Nir Alfasi
- 53,191
- 11
- 86
- 129

Demarco Mills
- 3
- 1
-
You need to first turn it into a list before passing to your function. Tuples are immutable – roganjosh Dec 04 '17 at 06:11
-
use list as an alternative if you want the tuple object to be edited. What is the problem in that? – HarshitMadhav Dec 04 '17 at 06:57
2 Answers
0
The problem is that eval(input("Please enter a list of numbers:"))
returns a tuple
which is immutable and you're trying to modify it here:
nums[i] = math.sqrt(nums[i])
It can be fixed by creating a list
instead:
nums = [x for x in eval(input("Please enter a list of numbers:"))]
Warning: eval is evil!

Nir Alfasi
- 53,191
- 11
- 86
- 129
0
The core problem is that the expression you enter into eval, such as "1, 2, 3" are tuples, which are immutable, i.e., unable to be changed.
Additionally, using eval like this is dangerous, and can lead to some confusing errors. (What happens if you put in an empty list?) Python has plenty of nice string manipulation functions, so it is also completely unnecessary. Try,
line = input('enter numbers:')
nums = [int(s.strip()) for s in line.strip().split(',') if s]

tahsmith
- 1,643
- 1
- 17
- 23