List Comprehension


#1

Hi. Is this correct?

foo = [‘3’, ‘4’, ‘5’]
foo = [eval(x) for x in foo]

Initially, the variable foo references the list [‘3’, ‘4’, ‘5’]. Then somewhere else, the new list [3, 4, 5] is created. foo now references this new list. The original list [‘3’, ‘4’, ‘5’] is garbage, and Python3 “destroys” it?

Thanks.


#2

Where does eval() come into this? We are not parsing for code, but simply parsing code.


#3

That depends on what you are trying to do. See Python 3: eval().

The following has been modified from your original example in order to demonstrate that each item in the list gets evaluated as code …

foo = ['3', '4', '5', 'print("Done!")' ]
foo = [eval(x) for x in foo]
print(foo)

Output …

Done!
[3, 4, 5, None]

Yes, you removed the only reference to that original list, and it gets garbage collected.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.