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

4

10

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?)

Grath answered 29/6, 2012 at 11:34 Comment(2)
@phg: That will result in 4 references to the same list.Subdual
@Ignacio Oh, right... I use to forget that, thanks!Meerkat
L
19

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.

Logrolling answered 29/6, 2012 at 11:45 Comment(0)
S
3

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

Subdual answered 29/6, 2012 at 11:43 Comment(0)
P
1
week_array = ['']*7
four_weeks = map(list, [week_array]*4)
Plenteous answered 29/6, 2012 at 11:54 Comment(0)
A
0

This is similar to other answers, in that I use map, but what I did uses the same function you are using.

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

Also, the main advantage compared to using _ for example is that it could already be used (_ is used by gettext often) and it changes its value in to the last item in the iterator. See this example:

[x for x in range(4)]
assert x == 3, 'x should be equal to 3'
Adversaria answered 29/6, 2012 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.