Python range examples

Python range can be used to generate a range of numbers with desired start number and gap. It is often used in for loops.

Usage:

range(stop)
range(start, stop[, step])

Here are some examples.

range to generate 0 to N-1

a = range(10)
print "type=%s" % (type(a))
print a
print "==outcome of for loop==="
for i in range(10):
  print i
type=<type 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
==outcome of for loop===
0
1
2
3
4
5
6
7
8
9
Env: Python 2.7.6

range with start, stop

This generates range from start to stop-1

for i in range(5,10):
  print i
5
6
7
8
9
Env: Python 2.7.6

range with start, stop, step

This generates range start, start+step,… Ntoe that outcome will not include stop.

for i in range(5,10, 3):
  print i
5
8
Env: Python 2.7.6

Additional notes

Note that if you are working on large data then it would be more memory efficient to use xrange.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments