Range():
- range() will create a list of values from start
to end (0 .. 20 in your example). This will become an expensive operation on
very large ranges.
range
returns a Pythonlist
object- range keeps the entire list of numbers in memory
- range() returns a list,
- Syntax: range(optional-start, last, optional-step)
… print i
…
0
1
2
3
4
5
6
7
8
9
…
0
1
2
3
4
5
6
7
8
9
XRange()
- xrange() on the other hand is much more optimised.
- it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.
xrange
returns anxrange
object.- xrange returns an iterator and only keeps one number in memory at a time.
xrange()
is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.
|
… print i
…
0
1
2
3
4
5
6
7
8
9
>>>
…
0
1
2
3
4
5
6
7
8
9
>>>
No comments:
Post a Comment