Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!