98

If I have a list comprehension (for example) like this:

['' for x in myList]

Effectively making a new list that has an empty string for every element in a list, I never use the x. Is there a cleaner way of writing this so I don't have to declare the unused x variable?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ramy
  • 20,541
  • 41
  • 103
  • 153
  • Inspired by this question, I created a youtube tutorial covering unused variables in list comprehensions https://www.youtube.com/watch?v=cZb5aFcpsAs – Brendan Metcalfe Jan 07 '21 at 03:17
  • Relevant: [PEP 640: Unused variable syntax](https://www.python.org/dev/peps/pep-0640/) (currently in "Draft" status), which proposes allowing `?` as placeholder. – 0 _ Apr 13 '21 at 05:08

10 Answers10

145

_ is a standard placeholder name for ignored members in a for-loop and tuple assignment, e.g.

['' for _ in myList]

[a+d for a, _, _, d, _ in fiveTuples]

BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.).

[''] * len(myList)
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 12
    The latter must be accompanied by a huge warning that it doesn't do the expected thing for mutable objects. –  Mar 29 '11 at 18:29
  • 5
    @Mohit: `a=[[]]*4;a[0].append(5);print(a)` – kennytm Mar 29 '11 at 18:32
  • @Ramy: Mohit posted an explanation but it was deleted :S Anyway, check Notes 2 in http://docs.python.org/py3k/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range. – kennytm Mar 30 '11 at 06:52
  • 2
    @Ramy, Python maintains the same reference for same object in memory. – Mohit Ranka Mar 30 '11 at 09:13
  • Does it matter if I'm doing nested `for` loops, for example? Or if inside `for _ in range(...)` I want to say `_, var = f(x)`? Will it get confused between the two `_` variables? – Eric Auld Jul 26 '18 at 21:44
  • 1
    @EricAuld it doesn't matter, the for loop doesn't rely on the variable name (`for i in range(3): for i in range(3): print('.')` will always print 9 dots). The inner variable will for sure shadow the outer one, but you're not supposed to read `_`. – kennytm Jul 27 '18 at 03:56
  • __ (double underscore) works the same if you don't want to ruin the possibility of using _ to mean last output in the interpreter – gss Jul 26 '19 at 19:41
19

No. As the Zen puts it: Special cases aren't special enough to break the rules. The special case being loops not using the items of the thing being iterated and the rule being that there's a "target" to unpack to.

You can, however, use _ as variable name, which is usually understood as "intentionally unused" (even PyLint etc. knows and respect this).

Rod
  • 52,748
  • 3
  • 38
  • 55
  • PyLint however complains that `C: 10,24: Invalid variable name "_" (invalid-name)` unless you add it to `good-names` in your `.pylintrc`. – giorgiosironi Jun 08 '16 at 08:22
13

It turns out that using dummy* (starting word is dummy) as the variable name does the same trick as _. _ is a known standard and it would be better to use meaningful variable names. So you can use dummy, dummy1, dummy_anything. By using these variable names PyLint won't complain.

Ram
  • 3,092
  • 10
  • 40
  • 56
Alfred
  • 336
  • 6
  • 12
2

Add the following comment after the for loop on the same line:

#pylint: disable=unused-variable

for i in range(100): #pylint: disable=unused-variable
1

If you need to name your arguments (in case, for example, when writing mocks that don't use certain arguments that are referenced by name), you can add this shortcut method:

def UnusedArgument(_):
  pass

and then use it like this

def SomeMethod(name_should_remain):
  UnusedArgument(name_should_remain)
kateroh
  • 4,382
  • 6
  • 43
  • 62
0

The generator objects don't actually use the variables. So something like

list(('' for x in myList))

should do the trick. Note that x is not defined as a variable outside of the generator comprehension.

highBandWidth
  • 16,751
  • 20
  • 84
  • 131
0

You can also prepend a variable name with _ if you prefer giving the variable a human readable name. For example you can use _foo, _foo1, _anything and PyLint won't complain. In a for loop, it would be like:

for _something in range(10):
    do_something_else()

edit: Add example

0

A verbose way is:

newList = []
while len(newList) < len(mylist):
    newList.append('')

You avoid declaring an used variable this way.

Also you can append both mutable and immutable objects (like dictionaries) into newList.

Another thing for python newbies like me, '_', 'dummy' are a bit disconcerting.

James Barton
  • 131
  • 1
  • 4
0

Try it, it's simple:

# Use '_' instead of the variable
for _ in range(any_number):
    do_somthing()
Gavriel Cohen
  • 4,355
  • 34
  • 39
-1

Comment to How can I get around declaring an unused variable in a for loop? (Ran out of comment size)

Python maintains the same reference for the object created. (irrespective of mutability),for example,

In [1]: i = 1

In [2]: j = 1

In [3]: id(i)
Out[3]: 142671248

In [4]: id(j)
Out[4]: 142671248

You, can see both i and j, refer to the same object in memory.What happens, when we change the value of one immutable variable.

In [5]: j = j+1

In [6]: id(i)
Out[6]: 142671248

In [7]: id(j)
Out[7]: 142671236

you can see j now starts to point a new location, (where 2 is stored), and i still points to location where 1 is stored. While evaluating,

j = j+1

The value is picked from 142671248, calculated(if not already cached), and put at a new location 142671236. j is made to point to the new location. In simpler terms a new copy made everytime an immutable variable is modified.

Mutability

Mutable objects act little different in this regard. When the value pointed by

In [16]: a = []

In [17]: b = a

In [18]: id(a)
Out[18]: 3071546412L

In [19]: id(b)
Out[19]: 3071546412L

Both a and b point to the same memory location.

In [20]: a.append(5)

Memory location pointed by a is modified.

In [21]: a
Out[21]: [5]

In [22]: b
Out[22]: [5]

In [23]: id(a)
Out[23]: 3071546412L

In [24]: id(b)
Out[24]: 3071546412L

Both a and b, still point to the same memory location. In other word, mutable variables act of the same memory location pointed by the variable, instead of making a copy of the value pointed by the variable, like in immutable variable case.

Community
  • 1
  • 1
Mohit Ranka
  • 4,193
  • 12
  • 41
  • 41