How to print something only if it exists?

Hans Mulder hansmu at xs4all.nl
Fri Sep 7 05:37:28 EDT 2012


On 6/09/12 19:59:05, 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.

How about:

     print day, fld[1], balance, fld[2] if len(fld) > 2 else ''


If you really want to avoid the keyword 'if', then you'd have to
do something like:

     print day, fld[1], balance, (fld[2:3] or [''])[0]

That may be shorter, but it isn't very readable.


Hope this helps,

-- HansM



More information about the Python-list mailing list