Home > Back-end >  List updation statement showing index out of range
List updation statement showing index out of range

Time:05-03

 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**

CodePudding user response:

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)
  • Related