I have a list (array) with mixed
a = ["x", "2", "y"]
b = ["x", 2, "y"]
print ":".join(a)
print ":".join(b)
The first join works, but the second one throws a TypeError exception
I came up with this, but is this the Python solution?
print ":".join(map(str, b))
BTW in the end I just would like to write this string to a file, so if there is a specific solution for that, I’d appreciate that too.
Your solution works nicely and is probably one of the fastest ways to do this for small to medium sized lists, but it creates an unnecessary list (in python2.x). Usually that’s not a problem, but in a few cases, depending on the object
b, it could be an issue. Another which is lazy in python2 as well as python 3 is:Some timings for python 2.7.3:
Some timings for python3.2:
Note that if you let the loop get a lot bigger, the differences become less important:
python2.7.3:
python 3.2.0
*all timings done on my MacbookPro, OS-X 10.5.8 intel core2duo ….
Notes,
mapis faster for a larger list.mapis probably slower for the small list as you need to look up the function whereas the list comprehension cannot be “shadowed”, so no lookup needs to be performed. There may be another turn-around point for HUGE lists where the time it takes to build the intermediate list becomes significant.