How to Implement a Python for Range Loop Without an Iterator Variable

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

Python for-loop without index and item

You can replace i with _ to make it an 'invisible' variable.

See related: What is the purpose of the single underscore "_" variable in Python?.

Loop in line in python without creating a variable that will not be used

If the function actually has to be called each time then this would work

def generate_float_population(count, size)
return map(generate_float_individual, [size] * count)

However if the same value is produced each time then

def generate_float_population(count, size)
return [generate_float_individual(size)] * count

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)

Skip over a value in the range function in python

You can use any of these:

# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
print i

# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
print i

# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
print i
if i == 49:
next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print i

Use list comprehension without iteration variable

Just discard the value of i:

a = [random.randrange(-10, 11) / 10 for _ in range(100)]

_ is considered the "last value" in Python and by convention is
used as a "throw away" value.

Getting the results of iteration using for x in range ()

You can store multiple values of sum by using an array or dictionary. I do not know anything about Tkinter but it appears you can use a function to set the text of a label (see answer to this question: How do I print an array in different lines in GUI window?)

It could look something like this:

min = 10
inc = 10
max = 40
sum = []

for i in range(min,max,inc):
sum.append(min + i)
print(sum[i])

def applytoLabel():
n = len(sum)
element = ''
for i in range(n):
element = element + sum[i]+'\n'
return element

label = tk.Label(canvas, text=applytoLabel(), font= "calibri 13", bg="white")

How to perform a while loop without setting a range in Python 3?

I think it's possible to calculate that infinite series to within your specified tolerance without using much memory at all, but based on how you wrote your code, I'm not sure if you have more requirements I'm just missing. Anyway, here's my attempt:

import numba as nb # optional speedup

@nb.njit # optional speedup
def pi(tol = 5e-11):
sign = 1
denom = 1
diff = 4/denom
calc = diff
while diff > tol:
sign *= -1
denom += 2
diff = 4/denom
calc += sign*diff
return calc

The numba lines are optional and are just for making it run faster during testing. I know you're not allowed to use libraries, and the code will work without the lines.



Related Topics



Leave a reply



Submit