How to print something only if it exists?

Dave Angel d at davea.name
Thu Sep 6 14:18:05 EDT 2012


On 09/06/2012 01:59 PM, 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".
>

Would you like to define "exists" ?  A list is not sparse, so all items
exist if their subscript is less than the length of the list.  So all
you need to do is compare 2 to len(fld).

But perhaps there's another approach.  Just what DO you want to print if
fld(1) exists, but fld(2) does not?  Do you still want to print out day,
fld(1), and balance?  Or do you want to skip balance as well?

if you literally want nothing printed for list elements beyond the end,
then I'd add some extra empty-strings to the end of the list.

fld.extend("" * 5)

Now, subscripts 0 through 4 inclusive will work, as specified.

Alternatively, perhaps there's some association between the day and the
fld(1), and the balance and the fld(2).  in that case, probably you want
to make a loop out of it, and only print each pair if they're both
available.  Something like:

      for tag, value in zip((something, day, balance), fld):
          print tag, value, ""


-- 

DaveA




More information about the Python-list mailing list