Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending data into an undeclared list

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?

like image 430
Pulimon Avatar asked Dec 08 '22 19:12

Pulimon


1 Answers

For your very base sample it can be done using list comprehension:

l = [x*x for x in range(0, 10)]
like image 159
Artsiom Rudzenka Avatar answered Dec 11 '22 09:12

Artsiom Rudzenka