0

I have a Python list:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

How do I print the list to get this output:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

The same as what is in my .py file?

A similar question appears for Go: Golang: print struct as it would appear in source code

But I do not understand it and if Python has anything similar.

For those wanting to know why, I need to print these lists to an HTML file. Due to limitations of programming interoperability and not wanting to over-engineer, this is easiest for me to use as code.

coolpy
  • 163
  • 1
  • 2
  • 14
  • 2
    https://stackoverflow.com/questions/32000934/python-print-a-variables-name-and-value Maybe this helps? – Chris Jan 17 '23 at 15:58
  • Did you try `print(L1)`? – Code-Apprentice Jan 17 '23 at 15:58
  • 7
    There is no way, given the list object, to get the `L1 = ` part in the print output, because the list **does not have** that information. Any object in Python can have **any number of names in the source code, including zero**. The Q&A you found for a different programming language doesn't solve that problem in the other programming language, either; and cannot, for a similar reason. – Karl Knechtel Jan 17 '23 at 15:59
  • 4
    Also what is the purpose of this? Smells like XY problem, maybe you should use dict, instead of name and value – buran Jan 17 '23 at 16:00
  • Are you okay with hardcoding the L1 name in the code that prints this? It's not clear what your requirements are. – user2357112 Jan 17 '23 at 16:11

2 Answers2

2

Use an f-string as follows:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

print(f'{L1 = }'.replace(', [', ',['))

Output:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

Without the call to replace() the output will be:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'], ['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

This is not a method I will not encourage you to use, but if you are really sure you want to do this you can do it like this.

I assume that you have a variable which you want to print.

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

# make a copy of the globals
g = globals().copy()

for key, value in g.items():
    if value is L1:
        break

print(f"{key} = {value}")

Again, I do not recommend you to use it.

3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18