Python Forum
list vs [] with range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: list vs [] with range (/thread-29767.html)



list vs [] with range - quazirfan - Sep-19-2020

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?


RE: list vs [] with range - bowlofred - Sep-19-2020

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



RE: list vs [] with range - deanhystad - Sep-19-2020

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.


RE: list vs [] with range - scidam - Sep-19-2020

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)].


RE: list vs [] with range - perfringo - Sep-19-2020

(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.


RE: list vs [] with range - deanhystad - Sep-19-2020

Thanks for the clarification. I'll have to study that some more.