Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most elegant way to write this for loop in Python?

Basically I want to go from -1 to 1 in n steps, including -1 and 1:

x = -1.0
n = 21

for i in range(n):
    print x
    x += 0.01

-1.0 -0.9 -0.8 ... 0.8 0.9 1.0

How can I write this in the most elegant, simplest way for any n value?

like image 773
Joan Venge Avatar asked Jan 02 '12 03:01

Joan Venge


People also ask

What is correct way to writing a for loop in Python?

for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).

What is better than for loop Python?

map() works way faster than for loop.


1 Answers

There is no built-in solution, but probably a good way to solve it is to define your own range function:

def my_range(start, end, how_many):
    incr = float(end - start)/(how_many - 1)
    return [start + i*incr for i in range(how_many)]

And you can use it in a for-loop:

>>> for i in my_range(-1, 1, 10):
...   print i
... 
-1.0
-0.777777777778
-0.555555555556
-0.333333333333
-0.111111111111
0.111111111111
0.333333333333
0.555555555556
0.777777777778
1

EDIT: As @NiklasBaumstark suggested, if your brand new my_range function is going to handle a big quantity of numbers it is probably a good idea to use generators. For that purpose, we'll do just a little modification:

def my_xrange(start, end, how_many):
        incr = float(end - start)/(how_many - 1)
        return (start + i*incr for i in xrange(how_many))
like image 117
juliomalegria Avatar answered Nov 15 '22 00:11

juliomalegria