1

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

asked Jul 24, 2022 at 6:48
1
  • you shouldn't edit the list within it's own iterator Commented Jul 24, 2022 at 6:51

2 Answers 2

2

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: []
answered Jul 24, 2022 at 6:59
Sign up to request clarification or add additional context in comments.

Comments

1

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/

answered Jul 24, 2022 at 7:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.