How to print something only if it exists?

Roy Smith roy at panix.com
Fri Sep 7 09:16:55 EDT 2012


In article <9s4nh9-8dr.ln1 at chris.zbmc.eu>, tinnews at isbd.co.uk wrote:

> I want to print a series of list elements some of which may not exist,
> e.g. I have a line:-
> 
>      print day, fld[1], balance, fld[2]
> 
> fld[2] doesn't always exist (fld is the result of a split) so the
> print fails when it isn't set.
> 
> I know I could simply use an if but ultimately there may be more
> elements of fld in the print and the print may well become more
> complex (most like will be formatted for example).  Thus it would be
> good if there was some way to say "print this if it exists".

One possible way is a trick I've used in the past.

fld = split(...) + ['']*10

this guarantees that fld has at least 10 elements.  If you want to 
guarantee that fld has *exactly* 10 elements, just take [0:10] of that.



More information about the Python-list mailing list