Home > Blockchain >  How remove() function was executed in python?
How remove() function was executed in python?

Time:03-26

Actually I was working with this code:

m=[0,1,2,3,4,5,6,7]
for i in m:
    m.remove(i)
print(m)

This looks pretty simple.

for i in m:
      print(i)

will print every elements in the list m. So the for part in our code will extract every elements of the list and remove it one by one. So the output that I except is [].

But I got [1,3,5,7].

How it can be the output and where I was wrong?

CodePudding user response:

What happens here is, you're removing items in the list on the go.

Eg,

  1. On the first remove() call, it removes 0 from the list (current index is 0).

  2. On the second remove() call, the current index is 1, but the list contains [1,2,3,...]. Now the the index 1 contains "2" instead of "1". Because 0 has been removed and the size of list is just changed.

So to clear list in python, you can use,

m.clear()

CodePudding user response:

when you use (for i in m), i starts from index zero so i is the element of index 0 which its value is 0 then in for loop you'll delete zero value.

now your list is [1,2,3,4,5,6,7] and i is the element of index 1 which its value is 2.

after deleting 2 your list would be like [2,3,4,5,6,7], now i is the element of index 2 which its value is 4 and ....

here is how this for loop works and why the output is like that.

to remove all element in a list you can use:

for i in range(len(m)):
    m.remove(m[0]) 

or

m.clear()

CodePudding user response:

If you know how to use a debugger, that would be the ideal way to diagnose this, otherwise, try running this code to see what's going on:

x = [0, 1, 2, 3, 4, 5, 6, 7]
for i in x.copy():
    x.remove(i)
    print(x)
print(x)


m = [0, 1, 2, 3, 4, 5, 6, 7]
for i in m:
    m.remove(i)
    print(m)
print(m)

During a given execution, the for loop accesses an element and then deletes it. For example, it first deletes the element at index 0, with value 0, leaving you with [1, 2, 3, 4, 5, 6, 7]. Then it moves on to the element at index 1, value 2, and deletes that, leaving you with [1, 3, 4, 5, 6, 7].

In general, avoid messing around with a list in Python. If you have to delete all elements, use m.clear(). If you have to delete some elements or do some other stuff, prefer to use list comprehension to create a new object.

CodePudding user response:

i don`t know why it is not remove each item, but i worked on it and it works like this:

m=[0,1,2,3,4,5,6,7]
while m != []:
    [m.remove(i) for i in m]
print(m)
  • Related