stefaanv stefaanv - 9 months ago 43
Python Question

In Python, is there an elegant way to print a list in a custom format without explicit looping?

I know you can do

print str(myList)

to get

[1, 2, 3]

and you can do

i = 0
for entry in myList:
print str(i) + ":", entry
i += 1

to get

0: 1
1: 2
2: 3

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Answer Source
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3

Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.