4

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']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
xssChauhan
  • 2,728
  • 2
  • 25
  • 36
  • 3
    `[] == list()` might give you the impression that `list()` is like e.g. `array()` in PHP – just an alternate syntax – but that’s not the case. It’s a type that gives an empty list when called with no arguments, converts an iterable to a list when called with one argument, and can’t be called with more than one argument. `[x]` is not equivalent to `list(x)`, and `list(x, y, …)` makes no sense. – Ry- Jun 23 '18 at 09:23

1 Answers1

13

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

user2390182
  • 72,016
  • 6
  • 67
  • 89