Creating a generator expression or list comprehension without the "x in" variable (for example, for a range) in Python

In Python, is there a way to write this list comprehension without the "x in" variable (since it remains completely unused)? The same applies to the expression of the generator. I doubt this happens very often, but I came across this several times and was curious to find out.

Here is an example:

week_array = ['']*7 four_weeks = [week_array[:] for x in range(4)] 

(Perhaps there is a more elegant way to build this?)

+6
source share
4 answers

I don’t believe that, and there is no harm in x . A common sign of when this value is not used is the use of underscore as a free variable, for example:

 [week_array[:] for _ in range(4)] 

But this is nothing more than a symbol that a free variable is not used.

+15
source

Not. Both constructs must have an iterator, even if its value is not used.

+2
source
 week_array = ['']*7 four_weeks = map(list, [week_array]*4) 
+1
source

This is similar to the other answers since I am using a map, but what I used uses the same function that you use.

 four_weeks = map(lambda i: week_array[:], range(4)) 

In addition, the main advantage over using _ , for example, is that it can already be used ( _ is often used by gettext), and it changes its value to the last element in the iterator. See this example:

 [x for x in range(4)] assert x == 3, 'x should be equal to 3' 
0
source

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


All Articles