In Python-3 filter
returns a generator (in Python-2 it returns a list), so it's evaluated when you consume it. But that wouldn't be a problem by itself, the problem is that your i
changes. At the time you consume the filter
your i = 5
and all your filter
just check for that.
I include some print
-statements so you can more easily follow what is happening:
l = range(2, 20)
for i in range(2, 6):
l = filter(lambda x: print(x, i) or (x == i or x % i != 0), l)
list(l)
2 5
2 5
2 5
2 5
3 5
3 5
3 5
3 5
4 5
4 5
4 5
4 5
5 5
5 5
5 5
5 5
6 5
6 5
6 5
6 5
7 5
7 5
7 5
7 5
8 5
8 5
8 5
8 5
9 5
9 5
9 5
9 5
10 5
11 5
11 5
11 5
11 5
12 5
12 5
12 5
12 5
13 5
13 5
13 5
13 5
14 5
14 5
14 5
14 5
15 5
16 5
16 5
16 5
16 5
17 5
17 5
17 5
17 5
18 5
18 5
18 5
18 5
19 5
19 5
19 5
19 5
[2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19]
That probably wasn't your intention. You could bind i
to your lambda:
l = range(2, 20)
for i in range(2, 6):
l = filter((lambda j: lambda x: print(x, j) or (x == j or x % j != 0))(i), l)
# or
# l = filter(lambda x, i=i: print(x, i) or (x == i or x % i != 0), l)
list(l)
2 2
2 3
2 4
2 5
3 2
3 3
3 4
3 5
4 2
5 2
5 3
5 4
5 5
6 2
7 2
7 3
7 4
7 5
8 2
9 2
9 3
10 2
11 2
11 3
11 4
11 5
12 2
13 2
13 3
13 4
13 5
14 2
15 2
15 3
16 2
17 2
17 3
17 4
17 5
18 2
19 2
19 3
19 4
19 5
[2, 3, 5, 7, 11, 13, 17, 19]
or cast your filter
-result immediatly to a tuple
:
l = range(2, 20)
for i in range(2, 6):
l = tuple(filter(lambda x: x == i or x % i != 0, l))
print(l)
# (2, 3, 5, 7, 11, 13, 17, 19)