How to Get Around Declaring an Unused Variable in a for Loop

How can I get around declaring an unused variable in a for loop?

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

How to avoid unused variable in a for loop error

You don't need to assign anything, just use for range, like this (on play)

package main

import (
"fmt"
"time"
)

func main() {
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for range ticker.C {
fmt.Println("Tick")
}
}()
time.Sleep(time.Second * 2)

}

Unused variable outside of a for-loop in Go

You can assign to a blank identifier just to be able to compile your code, like: _ = header. As example:

package main

import (
"encoding/csv"
"fmt"
"io"
"strings"
)

func main() {

in := `first_name,last_name,username
"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`
file := strings.NewReader(in)
inputData := csv.NewReader(file)
var header []string
//keep reading the file until EOF is reached
for j := 0; ; j++ {
i, err := inputData.Read()
if err == io.EOF {
break
}
if j == 0 {
header = i
} else {
// Business logic in here
fmt.Println(i)
//TODO convert to JSON
//TODO send to SQS
}
}

_ = header
}

https://go.dev/play/p/BrmYU2zAc9f

Golang complaining about unused variable inside for-loop

One way to make the error disappear would be to declare an err variable outside the loop:

var err error

That way, you can assign existing variables (rather than declare new variables) inside the loop

for _, backoff := range backoffSchedule {
response, err = client.Do(request)
^^^

Make sure this is what you want though, as response will be, outside the loop, the last value assigned in the loop.

Is is possible to create a for-of loop without a variable?

No, you can't, not in the general case.¹ You can use the iterator² directly, though:

const hasAny = xs => !xs[Symbol.iterator]().next().done;

Or if you want to ensure you proactively release any resources the iterator holds (rather than waiting for them to be released automatically — think DB connection in a generator function or similar), proactively call return on it if it provides a return (not all do) like for-of does under the covers:

const hasAny = xs => {
const it = xs[Symbol.iterator]();
const result = !it.next().done;
if (it.return) it.return();
return result;
};

Live Example:

const hasAny = xs => !xs[Symbol.iterator]().next().done;
console.log(hasAny([])); // falseconsole.log(hasAny([1])); // true

how do you make a For loop when you don't need index in python?

There is no "natural" way to loop n times without a counter variable in Python, and you should not resort to ugly hacks just to silence code analyzers.

In your case I would suggest one of the following:

  • Just ignore the PyLint warning (or filter reported warnings for one-character variables)
  • Configure PyLint to ignore variables named i, that are usually only used in for loops anyway.
  • Mark unused variables using a prefix, probably using the default _ (it's less distracting than dummy)

How to avoid annoying error declared and not used

That error is here to force you to write better code, and be sure to use everything you declare or import. It makes it easier to read code written by other people (you are always sure that all declared variables will be used), and avoid some possible dead code.

But, if you really want to skip this error, you can use the blank identifier (_) :

package main

import (
"fmt" // imported and not used: "fmt"
)

func main() {
i := 1 // i declared and not used
}

becomes

package main

import (
_ "fmt" // no more error
)

func main() {
i := 1 // no more error
_ = i
}

As said by kostix in the comments below, you can find the official position of the Go team in the FAQ:

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither.

Unused variable in Python

In order to be able to use variable sscount globally and to manipulate the global variable within function on_release , you have to declare sscount as global variable in the function using global sscount. Complete result:

def on_release(key):
global sscount
if key == Key.esc:
sscount = 0 #this is where the warning comes.
return False

Is it possible to implement a Python for range loop without an iterator variable?

Off the top of my head, no.

I think the best you could do is something like this:

def loop(f,n):
for i in xrange(n): f()

loop(lambda: <insert expression here>, 5)

But I think you can just live with the extra i variable.

Here is the option to use the _ variable, which in reality, is just another variable.

for _ in range(n):
do_something()

Note that _ is assigned the last result that returned in an interactive python session:

>>> 1+2
3
>>> _
3

For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.

>>> for _ in xrange(10): pass
...
>>> _
9
>>> 1+2
3
>>> _
9

And according to Python grammar, it is an acceptable variable name:

identifier ::= (letter|"_") (letter | digit | "_")*


Related Topics



Leave a reply



Submit