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

list(1) isn't iterable, but list('a') is. Quirk of Python or is there a reason for this?

^

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,154 Points

This is a case where list() is not the same as using bare brackets [ ] to define a list. The built-in function list() iterates over an single object and returns a list of the objects items. The brackets [ ] creates a list from the literal and object references listed between the brackets.

To get a list of of the number 1 using the list() function pass the integer as a tuple:

$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> list((1, ))
[1]

Cool, thanks.