May-17-2019, 07:14 PM
I am learning python and observed a curious thing while practicing.
I was playing around with filter and lambdas.
Question:
1. In the below script script1 i have converted the filter object into list and then tried to convert to tuple. What i observed was that the tuple resulted empty.
2. I thought may be filter does not like tuple :-).
I was curious if the sequence of conversion has something to do with this and changed the sequence. Now tuple first and then List script2.
Now, the list resulted empty
Can someone help me understand what is happening here and why?.
Script 1
I was playing around with filter and lambdas.
Question:
1. In the below script script1 i have converted the filter object into list and then tried to convert to tuple. What i observed was that the tuple resulted empty.
2. I thought may be filter does not like tuple :-).
I was curious if the sequence of conversion has something to do with this and changed the sequence. Now tuple first and then List script2.
Now, the list resulted empty
Can someone help me understand what is happening here and why?.
Script 1
print("Understanding FILTER") filtr = lambda x:x**2 res=filter(filtr,[0,1,2,3,0,5,4,0]) print("Filter Result Type:: ",type(res)) print("Filter ID:: ",id(res)) print("Filter Result (Converted to LIST ):: ",list(res)) print("Filter ID (Converted to LIST ):: ",id(res)) print("Filter Result (Converted to TUPLE):: ",tuple(res)) print("Filter ID (Converted to TUPLE):: ",id(res)) print("Filter Result Type:: ",type(res))Result 1
Understanding FILTER Filter Result Type:: <class 'filter'> Filter ID:: 178889392 Filter Result (Converted to LIST ):: [1, 2, 3, 5, 4] Filter ID (Converted to LIST ):: 178889392 Filter Result (Converted to TUPLE):: () Filter ID (Converted to TUPLE):: 178889392 Filter Result Type:: <class 'filter'>Script 2
print("Understanding FILTER") filtr = lambda x:x**2 res=filter(filtr,[0,1,2,3,0,5,4,0]) print("Filter Result Type:: ",type(res)) print("Filter ID:: ",id(res)) print("Filter Result (Converted to TUPLE):: ",tuple(res)) print("Filter ID (Converted to TUPLE):: ",id(res)) print("Filter Result (Converted to LIST ):: ",list(res)) print("Filter ID (Converted to LIST ):: ",id(res)) print("Filter Result Type:: ",type(res))Result 2
Understanding FILTER Filter Result Type:: <class 'filter'> Filter ID:: 178890176 Filter Result (Converted to TUPLE):: (1, 2, 3, 5, 4) Filter ID (Converted to TUPLE):: 178890176 Filter Result (Converted to LIST ):: [] Filter ID (Converted to LIST ):: 178890176 Filter Result Type:: <class 'filter'>