首页 > 解决方案 > Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why?

问题描述

I was experimenting with list properties while doing Python exercises on inheritance and class objects. I realised that list([1,2,3]) is valid as a list itself is an iterable but something like list(1) will return an error. Isn't a single object in itself an iterable? However, a string with multiple characters like list("this is a list") does not return an error, further adding to my confusion (Granted, a string is a single object). Why is that the case?

from  cpython/listobject.c (starting line 2675)
/*[clinic input]
list.__init__
    iterable: object(c_default="NULL") = ()
    /
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
[clinic start generated code]*/

I've looked at the source code for the list class at https://github.com/python/cpython/blob/master/Objects/listobject.c and it seems line 2675-2721 might have the answer I'm looking for but as a novice, I need someone to explain the process of creating a list to me.

标签: pythonlistiterable

解决方案


The list() function only accepts iterables. Iterables are objects that can be iterated over. There is no way a program can iterate over an integer, but it can iterate over a single-character string.


推荐阅读