-
-
Notifications
You must be signed in to change notification settings - Fork 30k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Strings beginning with underscore not removed from lists - feature or bug? #77338
Comments
Strings beginning with underscore not removed from lists Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test = ["a","_a","b","_b"]
>>> for i in test: print(i)
...
a
_a
b
_b
>>> for i in test: test.remove(i)
...
>>> test
['_a', '_b']
>>> Is this a feature or a bug? |
It's just the right behavior. You are modifying the list while iterating over it. It has no business of underscore. >>> test = ['_a', 'a', '_b', 'b']
>>> for i in test: test.remove(i)
>>> test
['a', 'b'] |
You may refer to stackoverflow for an explanation, for example, https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list |
In addition to Xiang Zhang's comments, this is neither a feature nor a bug, but a misunderstanding. This has nothing to do with strings or underscores: py> L = [1, 2, 3, 4, 5] When you modify a list as you iterate over it, the results can be unexpected. Don't do it. If you *must* modify a list that you are iterating over, you must do so backwards, so that you are only removing items from the end, not the beginning of the list: py> L = [1, 2, 3, 4, 5] But don't do that: it is nearly always must faster to make a copy of the list containing only the items you wish to keep, then assign back to the list using slicing. A list comprehension makes this an easy one-liner: py> L = [1, 2, 3, 4, 5] |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: