The output must be an empty list but I am getting 3. Literaly got confused in this silly problem.
j = [2,3,4]
lk = []
for i in j:
if i>=0:
j.remove(i)
print(j)
output = [3]
expected output = []
what is the issue here
CodePudding user response:
When you are looping it is iterating with reference to it's index.
In the first iteration ->
Index is 0 and Value is 2: 2 > 0, the value is getting removed from the list (j). Result: j=[3,4]
In the second iteration ->
Index is 1 and value becomes 4 (since you have removed 2 from j
): 4 > 0, the value is getting removed. Result: j=[3]
Now the size of the list is 1 (which is less than the current iterator value(2)), so the iteration stops and the list j
still has value 3
j=[3]
Trial code:
j = [2,3,4]
lk = []
for i in j:
if i>=0:
j.remove(i)
print(j)
Output:
[3, 4]
[3]
So, you shouldn't edit the list within it's own iterator. Instead create a copy and perform the operation:
Suggested code:
j = [2,3,4]
j_cpy = j.copy()
lk = []
for i in j_cpy:
if i>=0:
j.remove(i)
print(j)
print("Final j value: ", j)
Here you are iterating on j_cpy
and editing the list j
.
Output:
[3, 4]
[4]
[]
Final j value: []
CodePudding user response:
Use a lambda function, they are much simpler, and always work when removing items from lists according to boolean checks.
Example:
j = [2, 3, 4]
lk = []
j = list(filter(lambda x: not x >= 0, j))
print(j)
Here's a small tutorial on them: https://www.geeksforgeeks.org/lambda-filter-python-examples/