I came accross this snippet:
li = ['a', 'b', 'c']
print "\n".join(li)
The author says:
This is also a useful debugging trick when you're working with lists.
What is the trick here?
I came accross this snippet:
li = ['a', 'b', 'c']
print "\n".join(li)
The author says:
This is also a useful debugging trick when you're working with lists.
What is the trick here?
The "trick" is printing each of the elements of a list in separate lines, that's all.
The "trick" is that "\n".join(li)
takes less time to write all the elements of li on the display than the following code:
for x in li:
print li
If li has few elements, the difference isn't really perceived.
But test the difference with a long list, and it will be evident
The word "trick" is a little excessive, though.
Printing a list like that is useless for debugging:
(1) If any of the list items are not strings, you will get an exception.
(2) Your stdout may not be able to display the strings, resulting in an exception or just gibberish.
(3) You won't see the difference between (for example) tabs (\t
) and multiple spaces.
Much better:
Python 2.x : print repr(li)
Python 3.x : print(ascii(li))
Update Here's what can happen with print(li')
on Python 3.x (it's problem 2 above):
>>> li = ['\u0404']
>>> print(li)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python32\lib\encodings\cp850.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u0404' in position
2: character maps to <undefined>
Note that print li
"works" on Python 2.x only because repr()
is called implicitly. In general one should just do print repr(thing)
. Note also that print(li)
can fail on Python 3.x because it implicitly calls repr()
, not ascii()
Update 2 If you want to find all non-strings in a list, do it explicitly, don't rely on "tricks":
>>> def check_list(li):
... for x, v in enumerate(li):
... if not isinstance(v, (str, unicode)):
... print "Type %s (%r) at offset %d" % (type(v), v, x)
...
>>> check_list(['\xff', 2, u'\u0303', 4.0])
Type <type 'int'> (2) at offset 1
Type <type 'float'> (4.0) at offset 3