Maxx
Maxx

Reputation: 318

Passing a list as several arguments

I'm trying to use a list as arguments, using the :

>>> l = [1,2,3]
>>> print( *l )

I got an error :

File "<stdin>", line 1
t*
 ^
SyntaxError: invalid syntax

I'm using python 2.7 :

>>> import sys
>>> print sys.version
2.7.3 (default, Jan  2 2013, 13:56:14)
[GCC 4.7.2]

What am I missing ? Thank you ! :)

Upvotes: 1

Views: 106

Answers (4)

wolfrevo
wolfrevo

Reputation: 7303

Is this what you are searching for?

>>> l = [1, 2, 3]
>>> def x(*args):
...     print args[0]
...     print args
>>> x(*l)
1
(1, 2, 3)

If yes, take also a look at Arbitrary Argument Lists in the Python documenation.

Upvotes: 0

Neel
Neel

Reputation: 21243

If you want to use print as a function then you have to use __future__ or upgrade python to 3+

Upvotes: 0

user2357112
user2357112

Reputation: 280390

By default, print isn't a function in Python 2.7. To use the function instead of the statement in a given module, use a future statement:

from __future__ import print_function

This needs to go at the top of your file, before any code that isn't a future statement (or the module docstring), because the compiler needs to see future statements first to compile the rest of the module differently based on the future statement.

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239453

print is NOT a function in Python 2.7. It is a statement. So, you should do

print l           # [1, 2, 3]

If you want to use print as a function in Python 2.7, you should import print_function from __future__, like this

from __future__ import print_function
l = [1,2,3]
print(l)          # [1, 2, 3]
print(*l)         # 1 2 3

Upvotes: 2

Related Questions