Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to automatically unpack list that contains some 0 values in Python?

When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.

Name (varchar) Apples(int) Candies(int) Color (varchar)
John 5 0 Blue

If I unpack my query result like:

name, apples, candies, color = mylist

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ll get a NoneType error because candies values (in this example) is considered as None rather than 0.

The workaround I currently have is (which defeats the purpose and benefit of unpacking):

name = mylist[0]
if apples is None:
    apples = 0
else apples = mylist[1]
if candies is None:
    candies = 0
else candies = mylist[2]
color = mylist[3]

So my question is, is there anyway I can unpack mylist when one (or more) items have a value of 0 (and not null or None) without going through each one of them as "if x is None: x = 0"?

>Solution :

You can still using unpacking, just fix up the None values afterward.

name, apples, candies, color = mylist
if apples is None:
    apples = 0
if candies is None:
    candies = 0

If you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.

mylist = [0 if x is None else x for x in mylist]
name, apples, candies, color = mylist

I doubt that 0 is really being turned into None, you probably have NULL values in the table. You can use IFNULL() to convert them:

SELECT name, IFNULL(apples, 0), IFNULL(candies, 0), color
FROM tablename
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading