Hello, I am just learning python so bear with me.
I am trying to figure out why the output of the following two lines are different despite both of them returning a list.
In: [range(9)]
Out: [range(0, 9)]
In: list(range(9))
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8]
In: type([range(9)])
Out: list
In: type(list(range(9)))
Out: list
I am guessing for the 2nd approach I am passing a range object in a list constructor. Is my guess corrcet?
You are correct. The first one has a single object in the list, the second one is the expansion of the range and has the ints inside.
>>> len([range(9)])
1
>>> type([range(9)][0])
<class 'range'>
>>> len(list(range(9)))
9
In your example range(9) is a range object. A range object is an iterator that produces a sequence of integers. Wrapping [] around the range object makes it a list that contains a range object.
list(arg) is a function that creates a list. arg is an iterator that is used to generate elements for the list. Passing range(9) to list() uses range(9) as an iterator to generate integers zero through eight.
range
returns iterable object that produces sequence of numbers (from start to end). If you type help(list)
, you can see that list-constructur expects as its argument an iterable object. So, if you passed range
object to list
, list constructor would just unpack (traverse the iterable and build the list) content of the range object. However, if you type [range(9)]
, you put range
object directly into the list (without unpacking). Note, you can also unpack range as follows: [*range(9)]
.
(Sep-19-2020, 03:33 AM)deanhystad Wrote: [ -> ]A range object is an iterator that produces a sequence of integers.
There are iterables and iterators. Range is iterable but not iterator. Of course we can get iterator out of it as from any iterable but it doesn't change the fact that range is iterable and not iterator.
Iterators support next(), range does not; we can loop range without consuming it, range have length and supports indexing all of which is not possible with iterators.
Thanks for the clarification. I'll have to study that some more.