Python xrange examples

Python xrange can be used to generate a sequence of numbers with desired start number and gap. It is often used in for loops. It is more efficient than range for large data.

Usage:

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

Here are some examples.

xrange to generate 0 to N-1

Note that xrange does not return a list.

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

xrange with start, stop

This generates sequence from start to stop-1

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

xrange with start, stop, step

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

for i in xrange(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 than range.

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

Comments

Click here to write/view comments