I need this code to pop and insert 0 in the list at the end of the list. I know some alternate method but i need to know what i did wrong in this code.
for i in arr:
if i == 0:
arr.insert(-1, arr.pop(arr.index(i)))
print(arr)
result:
[4, 5, 1, 9, 0, 0, 5]
expected result :
[4, 5, 1, 9, 5, 0, 0]
CodePudding user response:
The direct reason is that you misunderstand how insert method works.
See this one: Array: Insert with negative index
The following code works fine instead. But don't change the elements of a list on iteration anyway.
arr = [4, 5, 0, 1, 9, 0, 5]
print(arr)
for i in arr:
if i == 0:
# arr.insert(-1, arr.pop(arr.index(i)))
arr.append(arr.pop(arr.index(i)))
print(arr)
CodePudding user response:
One possible approach would be just to sort the list using a lambda function to test each value for 0. For example:
print(sorted([4, 5, 0, 1, 9, 0, 5], key=lambda x: x == 0))
This would display:
[4, 5, 1, 9, 5, 0, 0]
Alternatively you could just build two arrays up as follows:
arr = [4, 5, 0, 1, 9, 0, 5]
values = []
zeros = []
for value in arr:
if value == 0:
zeros.append(value)
else:
values.append(value)
output = values zeros
print(output)
These approaches avoid trying to alter arr whilst iterating over it.
CodePudding user response:
You could rebuild the list in two parts, first filtering out zeros then adding the number of zeros at the end:
arr = [4, 5, 0, 1, 9, 0, 5]
arr = [*filter(None,arr),*[0]*arr.count(0)]
print(arr)
[4, 5, 1, 9, 5, 0, 0]
If you need to do it in-place, you can extend the list with zeros that you pop-out of it going backward (so that indexes remain stable):
arr = [4, 5, 0, 1, 9, 0, 5]
arr.extend(arr.pop(i) for i in reversed(range(len(arr))) if not arr[i])
print(arr)
[4, 5, 1, 9, 5, 0, 0]
Or use the equivalent for-loop:
for i in reversed(range(len(arr))):
if not arr[i]:
arr.append(arr.pop(i))
