Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generator expression or list comprehension without variable "x in" (e.g. for range) in Python

In Python, is there any way to write this list comprehension without the "x in" variable (since it is left completely unused)? Same applies to a generator expression. I doubt this comes up very often, but I stumbled onto this a few times and was curious to know.

Here's an example:

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

(Also perhaps, is there a more elegant way to build this?)

like image 620
TimY Avatar asked Jun 29 '12 11:06

TimY


2 Answers

I don't believe so, and there is no harm in the x. A common thing to see when a value is unused in this way is to use an underscore as the free variable, e.g.:

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

But it's nothing more than a convention to denote that the free variable goes unused.

like image 97
wim Avatar answered Sep 19 '22 00:09

wim


No. Both constructs must have an iterator, even if its value is unused.

like image 42
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 00:09

Ignacio Vazquez-Abrams