xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range()
returns a Python list, whereas, xrange()
returns an xrange object.
So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object type generators and has been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error
in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).
for i in xrange(10): # numbers from o to 9
print i # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10): # numbers from 1 to 9
print i # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2): # skip by two for next
print i # output => 1 3 5 7 9
<em style='-webkit-font-smoothing:subpixel-antialiased; background-color:#f8fcfd; border:0px; box-sizing:border-box; color:#7e868e; font-family:"Source Sans Pro",Helvetica,arial,nimbussansl,liberationsans,freesans,clean,sans-serif,"Segoe UI Emoji","Segoe UI Symbol"; font-size:15px; margin:0px; padding:0px; text-rendering:optimizelegibility; vertical-align:baselin