I'm wondering if CODE 2 requires 41880+ of memory space anyways, since I "created" a list... but perhaps not because I didn't store it in a variable?
In other words, are CODE 1 and CODE 2 similar in terms of occupied memory space?
# CODE 1
my_list = [l for l in range(5000)] # I occupied big space here (41880)
my_iter1 = iter(my_list)
# CODE 2
my_iter2 = iter([i for i in range(5000)]) # did I occupy big space here too?
In general, there's little difference between
and
Since Python is not a "lazy" language, they both have to calculate the expression's value fully, which means allocating all the memory for this value.
The only difference is that in the second version, the memory for the value of the expression will become garbage after
func()returns (unless the function saves it somewhere). In the first version, it does't become garbage until the variable is reassigned or deleted (if this code is in a function, this happens automatically when the function ends).