0

Trying to print list items on individual lines as simply as possible following this:

https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/

>>> myVar = [1, 2, 3, 4, 5]
>>> print(*myVar)
  File "<stdin>", line 1
    print(*myVar)
          ^
SyntaxError: invalid syntax

I must use Python 2.7.8, so I guess I have to translate that without () but I fail at this:

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

So, is this a syntax issue? Or is there a better way to do this on v2.7.8?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
L0Lock
  • 147
  • 13

1 Answers1

3

Python 2's print statement doesn't support argument unpacking (because it's not a function, so it has no arguments), but you can opt-in to using Python 3's print function even in Python 2, by adding the following to the very top of your file (before any line aside from a shebang line and file encoding comments I believe; __future__ imports are weird, and since they change the compiler behavior, they need to occur before any other code):

from __future__ import print_function

Once you do that, the print statement ceases to exist for that script, and you can use Python 3's print function normally, e.g. for your desired task of printing the values of myVar, one per line, you'd do:

print(*myVar, sep='\n')
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • That sounds like something really interesting. Will try tomorrow at work asap and let you know. Thanks anyway! – L0Lock Feb 17 '23 at 02:42
  • So.... It works perfectly on my terminal but not in the software that needs this script and uses the same python version. I guess I will have to make a for loop x) – L0Lock Feb 17 '23 at 15:35
  • @L0Lock: Are you running on a Python version from before 2.6? Because the `__future__` import should work in the early alpha releases of 2.6 and beyond. – ShadowRanger Feb 17 '23 at 16:08
  • Running `print(sys.version)` in the software in which I am running this script indicates it is using python 2.7.8 (and 2.7.11 when using the beta build). But tbh it's not the first time that something supposed to work on that python version do not work in that software, I guess some stuff are blocked. – L0Lock Feb 17 '23 at 19:07