Aug 24, 2018
Python has two handy functions for creating lists, or a range of integers that assist in making for loops.These functions are xrange and range. But you probably already guessed that! 🙂
Last updated
Python has two handy functions for creating lists, or a range of integers that assist in making for loops.These functions are xrange and range. But you probably already guessed that! 🙂
Last updated
xrange
and range
in PythonBefore we get started, let's talk about what makes xrange
and range
different.
For the most part, xrange
and range
are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range
returns a Python list
object and xrange
returns an xrange
object.
What does that mean? Good question! It means that xrange
doesn't actually generate a static list at run-time like range
does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. If you want to read more in depth about generators and the yield keyword, be sure to checkout the article .
Okay, now what does that mean? Another good question. That means that if you have a really gigantic range you'd like to generate a list for, say one billion, xrange
is the function to use. This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range
will use as much memory as it can to create your array of integers, which can result in a MemoryError
and crash your program. It's a memory hungry beast.
That being said, if you'd like to iterate over the list multiple times, it's probably better to use range
. This is because xrange
has to generate an integer object every time you access an index, whereas range
is a static list and the integers are already "there" to use.