Display a specific value from a list

I have type because it is a list from a mysql query

if I do

    tiporepor = obtener_report_por_id_user(db,usuario,agrupacion,tipo_repor)
    print(tiporepor)

The result of the query appears with its respective fields, type this

(2, 'Export', 'b0a6c218e48eee5', 'All', '', 'img', 'user', 4)

Now what I would like is to show only field 2 (Export), in fact I would like to verify if there is something in field 2 and if there is, show it. Type this but it doesn’t work for me…

is field 2 = null
	print("hello")

What you have there is a tuple, so you should be able to do the likes of:

if tiporepor[1]:
    print(tiporepor[1])
else:
    print("Field 2 is empty")

That assumes the said field will be present, if empty, otherwise you will not get the expected return.

edit: scrub that. I’ve just noticed that the output of
(2, 'Export', 'b0a6c218e48eee5', 'All', '', 'img', 'user', 4)
seems to be at odds with
(db,usuario,agrupacion,tipo_repor)

I have already been able to but like this:

tiporepor = obtener_report_por_id_user(db,usuario,agrupacion,tipo_repor)
    try:
        if tiporepor[0][2]:
            return render_template('panel_workspace.html', tiporepor=tiporepor, version=__version__)
    except IndexError:
        return render_template('panel_workspace_2.html', tiporepor=tiporepor, version=__version__)

Although I don’t know if it is the best way.

Sorry about my first reply. I got confused by the word ‘list’ in the thread title, which is why I went down that blind ally.

If what you have there works, I don’t see anything wrong with that and in fact, a try/except is as good a way as any.

You may want to do…
except IndexError as tiporepor_error:
…so that you have that reference (the object tiporepor_error) should it be needed, moving forward.

“Best” depends on what you like best and all kinds of things :slight_smile:

I would suggest either using collections.namedtuple or a little dataclasses.dataclass to deal with the return values of obtener_report_por_id_user. In the render_template function I would then also use that namedtuple class. This could make your code more readable and it would make it a lot easier to spot errors.

Example (just using two fields)

>>> from collections import namedtuple
>>> TipoReport = namedtuple("TipoReport", ("report_id", "tipo"), defaults=(0, None))  
>>> values = [0]
>>> report = TipoResult(*values)
>>> report.tipo is None
True
>>> values = [0, "Export"]
>>> report = TipoReport(*values)
>>> report.tipo
'Export'

Using namedtuple with defaults would require that the values are always a list or tuple of not more elements than you defined - so how usable it it depends on your obtener function. Using dataclasses will give you more flexibility (if you need it), at the cost of a little bit more coding.