# [Tutor] If/elif/else when a list is empty

Steven D'Aprano steve at pearwood.info
Tue Sep 14 14:45:31 CEST 2010

```On Tue, 14 Sep 2010 01:58:07 pm aeneas24 at priest.com wrote:

> if len(rgenre)>0:
>           if len(rgenre)>2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3=rgenre[2]
>           elif len(rgenre)==2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3="NA"
>           elif len(rgenre)==1:
>               rg1=rgenre[0]
>               rg2="NA"
>               rg3="NA"
>    else len(rgenre)<1: # I was hoping this would take care of the
> "there is no genre information" scenario but it doesn't
> rg1=rg2=rg3="NA"

The above will give a SyntaxError, because you can't have a condition
immediately after an else.

This is a neater way to write the above:

n = len(rgenre)
if n == 0:
rg1 = rg2 = rg3 = "NA"
elif n == 1:
rg1 = rgenre[0]
rg2 = rg3 = "NA"
elif n == 2:
rg1, rg2 = rgenre[0:2]
rg3 = "NA"
else:
rg1, rg2, rg3 = rgenre[:3]

which in turn can be shortened to the slightly cryptic one-liner:

rg1, rg2, rg3 = (rgenre + ["NA"]*3)[:3]