python - 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.
解决方案
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.
推荐阅读
- parallel-processing - 在 Julia 中使用 FLoops 进行并行化
- python - AssertionError: 收听前必须输入音源
- r - 值 [[3L]](cond) 中的错误:没有名为“plyr”的包
- html - HTML/CSS 将元素移动到其他地方
- gatsby - 如何为 netlify-cms-widget-mdx 提供范围和自定义组件
- java - 使用通配符泛型时的 Java 编译错误
- python - 机制 - 为什么使用相对导入直接在 main 上运行会导致“尝试在没有已知父包的情况下进行相对导入”
- sql - 多列不匹配查询 MS Access SQL
- http - 如何在 Go 中的 HTTP POST 请求正文中发送变量(在代码中声明)?
- arrays - 将函数链接到 onPress headerRight 按钮