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) Lists Redux Combining Lists

Joe di Stefano
PLUS
Joe di Stefano
Courses Plus Student 5,533 Points

Is list() necessary?

At 1:38 the teacher writes the following to create a new list:

our_list = list(range(10))

Since range() returns a list, I don't see the purpose of using list() here. Am I missing something?

2 Answers

Stone Preston
Stone Preston
42,016 Points

in Python 3.x, the range() constructor returns a range sequence type, not a list like it did in Python 2.x. So yes the call to list() is necessary to convert the range to a list. See the Range documentation for more information

From the documentation:

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Yep, almost nothing actually returns a list in Python 3. This is better behavior than Python 2's because now you can cast your range() or dict.keys() or whatever to whatever data type you actually want. One less step!