mdsingh mdsingh - 1 month ago 13
Python Question

List comprehension for printing dump

I have a list with huge amount of hex numbers. I want to print it in form of a dump (lets say 4 values in a line). I can do that with the following for loop:

#Trying to achieve this (printing values in lines of 3 from list):
for i,val in enumerate(my_list):
if( i!=0 and i%3 == 0 ):
print val
else:
print val,


I use the following list comprehension:

clist = [ val if i%3 == 0 else val, for i,val in enumerate(my_list) ]
print clist


This would give a syntax error. The error part I know is "val,". I know there would some difference is converting the above for loop into comprehension list than the way I usually do.
How should I convert the given for loop into a suitable comprehension list?

Answer

try a generator like this:

clist  = ( val+'' if (i+1)%3  else val+'\n' for i,val in enumerate(my_list) )

then print it like this:

for c in clist:
    print c,

--

edit:

if you don't want to iterate when printing, just prepare list and print it all at once:

clist = [val + (' ' if (i+1)%3 else '\n') for i,val in enumerate(my_list)]
print ''.join(clist)