Adding data to an undeclared list

From time to time, the following script appears when I code in Python:

I repeat the loop and find that I want to keep the intermediate values โ€‹โ€‹of the variable in a list that will be used later. The following is a very simple code example:

for x in range(0,10): y = x*x temp_list.append(y) 

The temp_list problem has not yet been announced. So I usually go 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) 

Although this may seem trivial, I'm just wondering if there is any pythonic way to create a list, if it doesn't exist, then add a value to it, and if it exists, just add?

+4
source share
3 answers

For your base sample, this can be done using a list comprehension:

 l = [x*x for x in range(0, 10)] 
+8
source

It should always be clear whether a variable is declared or not. How else would you like to access it?

What you can do dynamically is a dict entry:

 a = {} for x in range(0,10): y = x*x a.setdefault('temp_list', []).append(y) 

a['temp_list'] will be created only if necessary.

+3
source

Depending on your problem, a good โ€œpythonicโ€ way to deal with such a structure may be to abstract it into a generator. For your trivial example:

 def squares(): for x in range(0,10): y = x*x yield y 

Then:

 temp_list = [i for i in squares()] 

Very often, when you need such a temporary list, because you are performing a series of operations on your data, each of which is associated with a different cycle. Using generators instead can significantly improve performance and memory usage, as they result in only one cycle.

Note that for trivial examples it is usually easier to write a generator expression:

 temp_list = (x*x for x in range(0, 10)) 

If you need a not-very-pythonic way to do this, you can edit the locals dictionary, but this is not a good idea, as this leads to obfuscation of the code:

 for x in range(0, 10): y = x*x locals().setdefault('temp_list', []).append(y) 
+2
source

Source: https://habr.com/ru/post/1445459/


All Articles