Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Slices Introduction To Slices

Lorenzo Franceschini
Lorenzo Franceschini
8,463 Points

Differences between my_list = range(1:6) and my_list = list(range(1:6))

Are there differences if I use this statement:

my_list = range(1:6)

instead of

my_list = list(range(1:6))

? I'll get with both a list object, right?

2 Answers

Note that there's a big difference between python2 and python3 when working with ranges.

In Python2, the range function actually returns a plain list:

>>> type(range(1,10))
<type 'list'>

This is why in Python2, the explicit conversion to the list class is not required and you can simply use the output of the range function directly as a plain list.

In Python3 things change a little bit. The range function no longer returns a plain list, but an instance of the range class.

>>> type(range(1,5))
<class 'range'>

This object, even if it is not an actual list, can be iterated over and can be used in for loops, list comprehensions and all other looping constructs. However, if you want to use it as a plain list and apply to it all the operations that are specific to lists, you need to do an explicit type conversion by calling the list constructor method and pass to it the range object:

>>> type(range(1,10))
<class 'range'>
>>> type(list(range(1,10)))
<class 'list'>

Hope this helps.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Well... one's a range object and the other is a list.

You can't add ranges together like you can lists, and you can't easily see the contents. But, no, the end result, a collection of numbers from 1 through 5, is the same.