List updation statement showing index out of range - python

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

There's three issues with your code:
eval() on user input is risky business. Use ast.literal_eval() instead.
Your for loop has an off-by-one error. Remember that array indices start at zero in Python.
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

how to use assignment operator in list comprehension

i want to create a list of random integers
I want the value of num to be a random integer The following line of code gives me a syntax error
invalid syntax
i just want to know that is there any way to do this using list comprehension
numbers = [num for num in range(1,6) num = random.randint(1,10)]
Looking at your requirements, you aren't required to assign num.
To generate a list of random numbers simply do:
numbers = [random.randint(1,10) for _ in range(1,6)]
You can alternatively do:
numbers = random.sample(range(1,11),k=5) # k is the repeating count
You don't need the num variable, just use the random.randint() call.
numbers = [random.randint(1,10) for _ in range(1,6)]

From random to XPath

I have 3 random generated numbers with random function
random = random.sample(range(1, 10), 3)
print (random)
Result is: [1, 6, 8]
and have XPath where need to change result for each number from result
For 1st number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[1]/div'
For 2nd number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[6]/div'
For 3rd number:
'//*[#id="app"]/div/div[3]/div/div[1]/div[8]/div'
Tried with for loop but not working
for i in random:
'//*[#id="app"]/div/div[3]/div/div[1]/div['+ i[0] +']/div'
In this case, your loop
for i in random
iterates for each element in the random list. If you were to print out i in the loop, you'll find it is an element of the list rather than a list itself. So it doesn't make sense to index it like you have done: i[0].
However, if you remove the indexing and just use i, you will still encounter a new error - since i is an integer and not a string - you can't concatenate an integer with strings. So, to correct this, you should cast it like this: str(i) and then it should work.
So the final solution would be:
xpath = '//*[#id="app"]/div/div[3]/div/div[1]/div['+ str(i) +']/div'
Alternative:
You can use Python 3's f-strings to avoid the string concatenation and type conversion:
xpath = f'//*[#id="app"]/div/div[3]/div/div[1]/div[{i}]/div'

Index error:list assignment index out of range

I want to:
Take two inputs as integers separated by a space (but in string form).
Club them using A + B.
Convert this A + B to integer using int().
Store this integer value in list C.
My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a is going out of the range (it must be starting from 0 ending at 3)?
Why it is showing this error?
Why your error is occurring:
You can only reference an index of a list if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change the index 0, which does not exist as the list is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.
The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices
Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]

indexing error in list in python

B=l.append((l[i]+A+B))
l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ?
There are many problems in your code:
1) the append method does not return anything, so it does not make sense to write B = l.append(...)
2) The double parenthesis are confusing, the code you wrote is exactly equivalent to B.append(l[i]+A+B)
3) Finally, obviously, the index i must be a valid index for the list l, otherwise you will get an IndexError exception.
List index out of range means that i is greater than len(l) - 1 (since Python, and many other programming languages, use indexing that starts at 0 instead of 1, the last item in the list has index len(l) - 1, not just len(l).
Try debugging like so:
try:
B = l.append((l[i] + A + B))
except IndexError:
print "Appending from index", i, "to list l of length:", len(l)
raise
This will tell you the value of i and the length of l when the append fails so you can search for the problem.
Is this in a loop? It may help to show us the code of the loop. It could be that, even though you're increasing the length of l by appending to it, you're increasing i even faster, so that it eventually gets to be bigger than len(l) - 1.
Variable i is larger or equal to the size of the l array.

python : list index out of range error while iteratively popping elements

I have written a simple python program
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
This gives me error 'list index out of range' on line if l[i]==0:
After debugging I could figure out that i is getting incremented and list is getting reduced.
However, I have loop termination condition i < len(l). Then why I am getting such error?
You are reducing the length of your list l as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.
It looks like what you want to do is:
l = [x for x in l if x != 0]
which will return a copy of l without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x, since non-zero numbers evaluate to True.
There is no such thing as a loop termination condition of i < len(l), in the way you've written the code, because len(l) is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:
i = 0
while i < len(l):
if l[i] == 0:
l.pop(i)
else:
i += 1
The expression len(l) is evaluated only one time, at the moment the range() builtin is evaluated. The range object constructed at that time does not change; it can't possibly know anything about the object l.
P.S. l is a lousy name for a value! It looks like the numeral 1, or the capital letter I.
You're changing the size of the list while iterating over it, which is probably not what you want and is the cause of your error.
Edit: As others have answered and commented, list comprehensions are better as a first choice and especially so in response to this question. I offered this as an alternative for that reason, and while not the best answer, it still solves the problem.
So on that note, you could also use filter, which allows you to call a function to evaluate the items in the list you don't want.
Example:
>>> l = [1,2,3,0,0,1]
>>> filter(lambda x: x > 0, l)
[1, 2, 3]
Live and learn. Simple is better, except when you need things to be complex.
What Mark Rushakoff said is true, but if you iterate in the opposite direction, it is possible to remove elements from the list in the for-loop as well. E.g.,
x = [1,2,3,0,0,1]
for i in range(len(x)-1, -1, -1):
if x[i] == 0:
x.pop(i)
It's like a tall building that falls from top to bottom: even if it is in the middle of collapse, you still can "enter" into it and visit yet-to-be-collapsed floors.
I think the best way to solve this problem is:
l = [1, 2, 3, 0, 0, 1]
while 0 in l:
l.remove(0)
Instead of iterating over list I remove 0 until there aren't any 0 in list
List comprehension will lead you to a solution.
But the right way to copy a object in python is using python module copy - Shallow and deep copy operations.
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
If instead of this,
import copy
l=[1,2,3,0,0,1]
duplicate_l = copy.copy(l)
for i in range(0,len(l)):
if l[i]==0:
m.remove(i)
l = m
Then, your own code would have worked.
But for optimization, list comprehension is a good solution.
The problem was that you attempted to modify the list you were referencing within the loop that used the list len(). When you remove the item from the list, then the new len() is calculated on the next loop.
For example, after the first run, when you removed (i) using l.pop(i), that happened successfully but on the next loop the length of the list has changed so all index numbers have been shifted. To a certain point the loop attempts to run over a shorted list throwing the error.
Doing this outside the loop works, however it would be better to build and new list by first declaring and empty list before the loop, and later within the loop append everything you want to keep to the new list.
For those of you who may have come to the same problem.
I am using python 3.3.5. The above solution of using while loop did not work for me. Even if i put print (i) after len(l) it gave me an error. I ran the same code in command line (shell)[ window that pops up when we run a function] it runs without error. What i did was calculated len(l) outside the function in main program and passed the length as a parameter. It worked. Python is weird sometimes.
I think most solutions talk here about List Comprehension, but if you'd like to perform in place deletion and keep the space complexity to O(1); The solution is:
i = 0
for j in range(len(arr)):
if (arr[j] != 0):
arr[i] = arr[j]
i +=1
arr = arr[:i]
x=[]
x = [int(i) for i in input().split()]
i = 0
while i < len(x):
print(x[i])
if(x[i]%5)==0:
del x[i]
else:
i += 1
print(*x)
Code:
while True:
n += 1
try:
DATA[n]['message']['text']
except:
key = DATA[n-1]['message']['text']
break
Console :
Traceback (most recent call last):
File "botnet.py", line 82, in <module>
key =DATA[n-1]['message']['text']
IndexError: list index out of range
I recently had a similar problem and I found that I need to decrease the list index by one.
So instead of:
if l[i]==0:
You can try:
if l[i-1]==0:
Because the list indices start at 0 and your range will go just one above that.

Categories