Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - What is the difference between a list of a single iterable `list(x)` vs `[x]`?

Python seems to differentiate between [x] and list(x) when making a list object, where x is an iterable. Why this difference?

>>> a = [dict(a=1)]
>>> a
[{'a': 1}]

>>> a = list(dict(a=1))
>>> a
['a']

While the 1st expression seems to work as expected, the 2nd expression works more like iterating a dict this way:

>>> l = []
>>> for e in {'a': 1}:
...     l.append(e)
>>> l
['a']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[x] is a list containing the element x.

list(x) takes x (which must already be iterable!) and turns it into a list.

>>> [1]  # list literal
[1]
>>> ['abc']  # list containing 'abc'
['abc']
>>> list(1)
# TypeError
>>> list((1,))  # list constructor
[1]
>>> list('abc')  # strings are iterables
['a', 'b', 'c']  # turns string into list!

The list constructor list(...) - like all of python's built-in collection types (set, list, tuple, collections.deque, etc.) - can take a single iterable argument and convert it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...