1
 List=eval(input('enter list of numbers and string :'))
    for x in range(1,len(List)+1,2):
        List[x]=List[x]*2
    print(List)

i want to update value at odd index but, why i don't know the statement 3 is generating error**List[x]=List[x]2 showing me error -index out of range**

1 Answers1

1

There's three issues with your code:

  1. eval() on user input is risky business. Use ast.literal_eval() instead.
  2. Your for loop has an off-by-one error. Remember that array indices start at zero in Python.
  3. List is not a good variable name, as it conflicts with List from the typing module. Use something like lst instead.
import ast
lst = ast.literal_eval(input('enter list of numbers and string :'))
for x in range(0, len(lst), 2):
    lst[x] = lst[x] * 2
print(lst)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • I have to repeat what @BrokenBenchmark wrote, because it can't be said too often.. Under no circumstance should you **ever** use eval on user input. The user can type anything--delete all the files in my home directory--and Python will happily do it. `eval` should be used rarely, and only with input that you control. – Frank Yellin May 03 '22 at 05:18
  • can you please tell me the difference between using eval and ast.litreal_eval. Is there any advantage in using ast.literal_eval – Sahil Panhalkar May 03 '22 at 14:13
  • See [here](https://docs.python.org/3/library/ast.html#ast.literal_eval). – BrokenBenchmark May 03 '22 at 14:51