from sys import stderr
from copy import copy
N = 5
L1 = list(range(1,N + 1)) #[1,2,3,4,5]
print("L1 =", L1, file = stderr)
L2 = map(lambda i: i ** 2, L1)
L3 = map(lambda i: i ** 2, L1)
L4 = copy(L2)
L5 = [i ** 2 for i in L1]
L6 = list(map(lambda i: i ** 2, L1))
print("L2 =", list(L2)) #[1,4,9,16,25]
print("L2 =", list(L2)) #[1,4,9,16,25]I think ... ?? ??
print("L3 =", list(L3)) #[1,4,9,16,25]
print("L4 =", list(L4)) #[1,4,9,16,25]I think ... ?? ??
print("L5 =", list(L5)) #[1,4,9,16,25]
print("L5 =", list(L5)) #[1,4,9,16,25]
print("L6 =", list(L6)) #[1,4,9,16,25]
print("L6 =", list(L6)) #[1,4,9,16,25]
print("L1 =", L1)
L1 = [1, 2, 3, 4, 5]
L2 = [1, 4, 9, 16, 25]
L2 = []
L3 = [1, 4, 9, 16, 25]
L4 = []
L5 = [1, 4, 9, 16, 25]
L5 = [1, 4, 9, 16, 25]
L6 = [1, 4, 9, 16, 25]
L6 = [1, 4, 9, 16, 25]
L1 = [1, 2, 3, 4, 5]
What you can see from this is that the access to the object created by ** map is valid only once ** (L2
・ L3
). ** Moreover, it was useless to make a shallow copy (L4
) with copy.copy
. ** Use list comprehension ** when accessing multiple times (L5
, but ** square brackets on the outside **) or ** instantly list or tuple ** (L6
) Should be. ** When you have to debug the contents of a map object, you may be addicted to an unexplained bug due to these characteristics only when debugging. ** **
As pointed out in the comment section, ** If you use parentheses to indicate the generator comprehension, it will be disposable like map. ** **
Basically, you can avoid situations like L2
and L4
by making the access only once after generation (including making a list or tuple like L6
).
range
, zip
, etc. will generate similar objects, but they may also be disposable . </ del>. Please be careful when accessing multiple times (from the comment).
Recommended Posts