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 type check a nested list of integers and convert to string?

If I have kwargs that have list and integer values, how do I type check the items in a for if loop?
I keep getting TypeError: 'int' is not iterable or it skips the if statement.

I’ve tried operators ==, !=, is, is not with list, List, iter, type(list) and int

Example:
If my kwargs are…

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

kwargs = {'foo': [1, 2], 'bar': 2, 'baz': 3}
new_list = []
for kw, args in kwargs.items():
    if args == list:
        for arg in args:
            new_list.append(str(arg))
    else:
        new_list.append(str(args))
print(new_list)
>>> ['[1, 2]', '2', '3']

and if I switch the if statement to if args != int: I get TypeError: 'int' is not iterable

>Solution :

To check if a variable is a list you can simply write:

if isinstance(var, list):
    pass

But if a variable could be anything iterable, use typing module.

from typing import Iterable  # or from collections.abc import Iterable

if isinstance(var, Iterable):
    pass

There are many other abstract base classes you can use, so I would suggest reading the documentation to learn about them.

https://docs.python.org/3/library/typing.html

https://docs.python.org/3/library/collections.abc.html

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