1

When creating lists in python, the two easy methods are list(arg) and [args]. However, only one of these allows multiple arguments, even though both result in an object of type list. Example:

>>> a=list('foo')
>>> type(a)
<class 'list'>
>>> a=list('foo','bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list() takes at most 1 argument (2 given)
>>> a=['foo','bar']
>>> a
['foo', 'bar']
>>> type(a)
<class 'list'>

Why is only the implicit call to list() via brackets valid?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
HelpfulHound
  • 326
  • 2
  • 9
  • 5
    `[]` is not a function, you aren't passing arguments to it. It is part of a list-literal, and even if it were a function, it works differently than `list`. `[]` is **not** and implicit call to `list`. – juanpa.arrivillaga Oct 30 '19 at 21:13

2 Answers2

3

Brackets enclose a list display (AKA list literal), and there is no implicit call to list().

list() takes only one argument because it expects an iterable. For example in list('foo'), the output is ['f', 'o', 'o'], not ['foo'].

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

The list constructor is designed for two cases: to only accept an empty argument and return a new empty list, or to accept an iterable that will be expanded into a list of the separate items within the iterable.

A single string is an iterable, but two strings separated by a comma is not, so:

>>> list('foo')
['f', 'o', 'o']

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |
 |  Methods defined here:
...
mgrollins
  • 641
  • 3
  • 9