'List updation statement showing index out of range
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**
Solution 1:[1]
There's three issues with your code:
eval()on user input is risky business. Useast.literal_eval()instead.- Your
forloop has an off-by-one error. Remember that array indices start at zero in Python. Listis not a good variable name, as it conflicts withListfrom thetypingmodule. Use something likelstinstead.
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
