Concise way to create single member list in Python?

Viewed 4257

Suppose I have some object x that may be a single instance of a data type (say float) or it may be a list of float types.

Is there any what I can ensure that x is wrapped as a list, perhaps being a singleton list if necessary, without checking its type or doing anything like that.

I'd like for something like list(x) to just always work, whether x was a singleton or not, but this doesn't work since a singleton isn't iterable.

Edit: see my answer below for some elaboration.

At the same time, I don't want to define my own function to construct lists from singeltons, and I don't want to do anything inline like this either:

from collections import Iterable
y = [x] if not isinstance(x, Iterable) else list(x)

If nothing more concise than this exists, that's OK. I am looking for some clean way of doing this that's already built into the language.

I'm sure some may think the isinstance approach is clean and good, but I'm specifically looking for something more concise that doesn't require me to write anything new before hand. I just can't find anything when searching doc pages and I'm not sure how to ask this question to a search engine.

3 Answers
Related