1
I’m trying to delete an item within a loop. I’ve heard it’s not possible. I’m seeing how to implement a comprehensive list.
But I still don’t understand how it works. I tried to do so:
result = [x for x in range(0, len(list)) if list[x][0] != 0 and list[x][1] != 0]
But it does not return me the list without the positions I want, only returns the clues.
Code below so far and that is giving error:
list = [
[1,2],
[3,4],
[5,6],
[0,0],
[7,8]
]
for x in range(0, len(list)):
if list[x][0] == 0 and list[x][1] == 0:
del list[x]
Error:
Indexerror: list index out of range
Now I’ve done so:
result = [list[x] for x in range(0, len(list)) if list[x][0] != 0 and list[x][1] != 0]
... And returned to the list without the positions I wanted. That’s how it is?
A question that came, on a list
[0, 1, 2, 3]
thelen()
of it would be 4, right? in case when making a loop should use... range(0, leng(...) - 1)
? Since the first index is 0 and the last index is 3 and not 1 and 4– Costamilam
@Guilhermecostamilam Yes, the size would be 4, but the
range(a, b)
python sets a range[a, b[
, I mean, it goes froma
untilb-1
. For example,range(0, 4)
would be[0, 1, 2, 3]
.– Woss