How to type check a nested list of integers and convert to string?

350 Views Asked by At

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...

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

1

There are 1 best solutions below

0
ccre On BEST ANSWER

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