0

The python documentary says that filter() returns an iterator so why is the last list empty

Also tried putting list() and iter() around the last f and those didn't help.

li = [1,2,3,4,5,6,7,8,9,10]

def func(x):
    return x**x

print([func(x) for x in li if x%2==0])

f = filter(lambda i: i%2==0,li)
print(f)
print(list(f))
m = map(func,iter(f))
print(list(m))

Output:

[4, 256, 46656, 16777216, 10000000000]
<filter object at 0x100c57e80>
[2, 4, 6, 8, 10]
[]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ngc1300
  • 138
  • 7
  • 5
    Iterators only iterate once. You consumed `f` when you built a `list` out of it. – Samwise Mar 02 '22 at 00:46
  • @Samwise Thanks. But then shouldn't map(func,iter(f)) have worked? It didn't tho – ngc1300 Mar 02 '22 at 00:52
  • Yes people I know I didn't post code. Was in a lazy mood and this code is so simple it shouldn't matter – ngc1300 Mar 02 '22 at 00:53
  • @pmac I was going to explain, but suddenly I'm in a lazy mood. (Also, how is it easier to snap a screenshot, crop it, and upload it than to just Ctrl-A/Ctrl-C/Ctrl-V the text???) – Samwise Mar 02 '22 at 00:53
  • @Samwise Haha taste of my own medicine. But it would be much appreciated if you could please explain. I've only been using python for a few weeks. – ngc1300 Mar 02 '22 at 00:56
  • @Samwise yea idk there i changed it – ngc1300 Mar 02 '22 at 00:59
  • @Samwise nvm, I see saving it to a variable name will allow me to use it again and again – ngc1300 Mar 02 '22 at 01:11

0 Answers0