Saltar al contenido.

Pythonic Encounter Series – Unpacking in Conditional Expressions

Hello,

Here comes a Pythonic Encounter that kept me entertained for a while debugging until I realised what as actually going… :-)

I’ve been using Python conditional expressions for a while now, at least the simplest in the form of:

 expression1 if condition else expression2

However, yesterday I was faced with a situation that although now looks very obvious on the moment of typing this little detail was not sparking in my mind.

# pretty clear code that makes use of list and zip
# to unpack a list of tuples to two separated lists of tuples
# or in this case just a tuple because there is only one element
a = [("1", "2"), ("", "")]
b, c = list(zip(*a))
print(b)
print(c)
('1', '')
('2', '')

I wanted to make use of conditional expressions to pass two lists with empty strings to variables b and c in the case the condition was evaluated to False. However, I was receiving an unexpected output (and took me a while to understand from where and why).

So, what is wrong with the following expression?

# here I would expect the same as before, however...
a = [("1", "2"), ("", "")]
# notice that the if True is just an example of 
# a conditional that I was expecting to evaluate to True in
# most cases.
b, c = list(zip(*a)) if True else [""], [""]
print(b)
print(c)
# ¡unexpected output!
[('1', ''), ('2', '')]
['']

Why was the two lists with empty strings inside not being passed to b and c? It was only after I posted a thread in Python-forum.io that a spark light on my mind!

Solution: The conditional expression ended in the comma (,), so the result from the conditional was being assigned to b and the [“”] to c. Hence, the following code gave the expected output:

a = [("1", "2"), ("", "")]
b, c = list(zip(*a)) if True else ([""], [""])
print(b)
print(c)
('1', '')
('2', '')

 

And that’s it, my yesterday Pythonic encounter. The solution was quite easy and obvious, but, interesting nonetheless. Take home message, sometimes is better to enclose expressions in brackets, it corrects and clarifies things :-P

Cheers,

João

¡Cuéntanos algo!

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s

Views / Visitas

  • 21.698 cientific@s mochiler@s

Antiguallas

Introduce tu dirección de correo electrónico para seguir este Blog y recibir las notificaciones de las nuevas publicaciones en tu buzón de correo electrónico.

Write your e-mail to start following this blog and get updates on new posts via e-mail.

A %d blogueros les gusta esto: