Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a list in print for Python 2

I'm having problem with understanding why unpacking does not work with list and print statement in Python 2.7:

>>> l=['a', 'b', 'c']
>>> print (*l, sep='')

Python 3.x works fine and prints:

abc

Python 2.7, however, raises an error:

 print (*l, sep='')
       ^
SyntaxError: invalid syntax

How can I make it work for Python 2.7?

I know I can alternatively code it using join with: ''.join(l)

like image 471
user1898781 Avatar asked Dec 08 '16 19:12

user1898781


2 Answers

Because print isn't a function in Python 2; unpacking a list and providing it as positional args isn't possible if it isn't a function.

You'll need to import the print_function from __future__ in order to support this:

>>> from __future__ import print_function

Now unpacking is possible:

>>> l = ['a', 'b', 'c']
>>> print(*l, sep='')
abc
like image 98
Dimitris Fasarakis Hilliard Avatar answered Sep 17 '22 20:09

Dimitris Fasarakis Hilliard


You have two options:

  • Convert to strings and join with spaces manually:

    print ''.join(map(str, l))
    
  • Use the print() function, by using the from __future__ import that disables the print statement:

    from __future__ import print_function
    
    print(*l, sep='')
    

    or directly call the function by accessing it via the __builtin__ module:

    import __builtin__
    print_function = getattr(__builtin__, 'print')
    
    print_function(*l, sep='')
    

    The same function is available in both Python 2 and 3, but in Python 2 you can't use it directly without first disabling keyword.

like image 45
Martijn Pieters Avatar answered Sep 18 '22 20:09

Martijn Pieters