Evgeny
Evgeny

Reputation: 4571

wrap elements to list in python

I'm looking to wrap string or dictionary into a list and came up with following straightforward code. Are there any more expressive/concise/'pythonic' ways todo that?

def iterate(x):
    if isinstance(x, list):
        return x
    elif isinstance(x, str) or isinstance(x, dict):
        return [x]
    else:
        raise TypeError(x)

assert iterate('abc') == ['abc']
assert iterate(dict(abc=1)) == [dict(abc=1)]
assert iterate([1, 2]) == [1, 2]

Update: Edited after @Bubble:

def iterate(x):
    if isinstance(x, (list, tuple)):
        return x
    elif isinstance(x, (str, dict)):
        return [x]
    else:
        raise TypeError(x)

Upvotes: 0

Views: 371

Answers (1)

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

It seems fine, the only thing I can think of is you can use a tuple in isinstance, so isinstance(x, (str, dict)) does the same thing as the isinstance(x, str) or isinstance(x, dict).

Upvotes: 2

Related Questions