Every once in a while the following scenario turns up while I code in Python:
I iterate through a loop and find that I want to store the intermediate values of a variable in a list to be used later. Following is a very basic sample code:
for x in range(0,10):
y = x*x
temp_list.append(y)
The problem is temp_list
has not been declared yet. So I usually navigate to the top of the loop and then add the following:
temp_list = []
for x in range(0,10):
y = x*x
temp_list.append(y)
While this may seem trivial, I was just wondering whether there is any pythonic way to create a list if it does not exist and then append a value to it, or else if it exists, just append?
For your very base sample it can be done using list comprehension:
l = [x*x for x in range(0, 10)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With