This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: list(filter) returns [] ???
Type: behavior Stage: resolved
Components: Demos and Tools Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ned.deily, remi.lapeyre, zhusu.china
Priority: normal Keywords:

Created on 2019-08-01 16:23 by zhusu.china, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg348864 - (view) Author: Su Zhu (zhusu.china) Date: 2019-08-01 16:23
The filter become empty after serving as an argument of list().

Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = filter(lambda x:x, [1,2,3])
>>> list(a)
[1, 2, 3]
>>> list(a)
[]
msg348865 - (view) Author: Rémi Lapeyre (remi.lapeyre) * Date: 2019-08-01 16:26
Hi Su Zhu, this is expected, as per the documentation, filter returns an iterable and not a list. The first `list(a)` consumes the iterable so it is empty when doing the second `list(a)`. You can see the same behavior when creating an iterable manually:

>>> a = iter([1, 2, 3])
>>> list(a)
[1, 2, 3]
>>> list(a)
[]

If you need to keep the result in a list, you can do:

>>> a = list(filter(lambda x:x, [1,2,3]))
msg348866 - (view) Author: Ned Deily (ned.deily) * (Python committer) Date: 2019-08-01 16:30
https://docs.python.org/3/library/functions.html#filter
msg348882 - (view) Author: Su Zhu (zhusu.china) Date: 2019-08-02 01:51
I see. Thank you very much!
History
Date User Action Args
2022-04-11 14:59:18adminsetgithub: 81920
2019-08-02 01:51:07zhusu.chinasetmessages: + msg348882
2019-08-01 16:30:26ned.deilysetstatus: open -> closed

nosy: + ned.deily
messages: + msg348866

resolution: not a bug
stage: resolved
2019-08-01 16:26:32remi.lapeyresetnosy: + remi.lapeyre
messages: + msg348865
2019-08-01 16:23:02zhusu.chinacreate