Python: list of a single iterable `list(x)` vs `[x]`

前端 未结 1 588
梦如初夏
梦如初夏 2020-12-03 23:45

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

相关标签:
1条回答
  • 2020-12-04 00:31

    [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.

    0 讨论(0)
提交回复
热议问题