3

Is there a way to init a list without using square bracket in Python?

For example, is there a function like list_cons so that:

x = list_cons(1, 2, 3, 4)

is equivalent to:

x = [1, 2, 3, 4]
Eitan T
  • 32,660
  • 14
  • 72
  • 109
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 9
    Why would you want to do that? – Ry- Jul 03 '12 at 20:23
  • 2
    Judging by the `functional-programming` tag and use of the term `cons`, it would seem the asker is trying to get Python to be as much like Lisp as possible. But then, why not just use Lisp? If for some reason an underlying Python implementation is required (to make use of Python libraries or something), then maybe check out the various Lisp-in-Python implementations [here](http://www.biostat.wisc.edu/~annis/creations/PyLisp/) (the linked page has further links to other implementations). – John Y Jul 03 '12 at 20:55
  • A Python list is not a cons/linked list, it's an array, so if you think you want this, you've probably mislead yourself badly. – abarnert Jul 03 '12 at 22:03

4 Answers4

11
In [1]: def list_cons(*args):
   ...:     return list(args)
   ...: 

In [2]: list_cons(1,2,3,4)
Out[2]: [1, 2, 3, 4]
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
6

Use the list constructor and pass it a tuple.

x = list((1,2,3,4))
robert
  • 33,242
  • 8
  • 53
  • 74
6

I don't think that would be a particularly useful function. Is typing brackets so hard? Perhaps we could give you a more useful answer if you explained why you want this.

Still, here's a fun thing you can do in Python 3:

>>> (*x,) = 1, 2, 3, 4, 5
>>> x
[1, 2, 3, 4, 5]

You can even omit the parenthesis -- *x, = 1, 2, 3, 4, 5 works too.

senderle
  • 145,869
  • 36
  • 209
  • 233
  • 3
    Didn't know of that yet, so +1. But I hope I'll never stumble upon this in production code ;-) – Oben Sonne Jul 03 '12 at 20:33
  • 1
    Why does it make a list and not any other iterable? – Dhara Jul 03 '12 at 20:34
  • 2
    @Dhara, the short answer is "[because](http://www.python.org/dev/peps/pep-3132/)." Consider [this question](http://stackoverflow.com/questions/6967632/getting-python-sequence-assignments-unpacking-right) for more corner cases. – senderle Jul 03 '12 at 20:37
  • @Dhara, less flippantly, the PEP I linked to says that using a tuple (and presumably any other type of iterable) would "make further processing of the result harder." (See the [third bullet point](http://www.python.org/dev/peps/pep-3132/#acceptance).) – senderle Jul 03 '12 at 20:42
1

works only in python 2.x:

>>> def list_cons(*args):
       return map(None,args)

>>> list_cons(1,2,3,4)
[1, 2, 3, 4]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504