Python list() function update to accept a non-iterable?

I’ve been working on a “learning project” which involves several short single-parameter functions, where the parameter might be either a numeric type or a list of numerics. E.g.,

def magnitude_of(v):
    try:
        return math.sqrt(sum([vi**2 for vi in v]))
    except:
        return abs(v)

This of course is necessary because if I did this:

def magnitude_of(v):
    return math.sqrt(sum([vi**2 for vi in list(v)]))

…the code would fail because list() only accepts an iterable as an argument.

My question is: has there ever been consideration given at PSW to letting list() work with any argument? If so, what prevented the change from being implemented?

Answer

I would just create my own list function and use it for this particular purpose.

Ex:

def mlist(v):
    try:
        return list(v)
    except(TypeError):
        return [v]

Now you use mlist instead of list

l1 = mlist(1)
l2 = mlist([1])

Both will give [1] as the result

Leave a Reply

Your email address will not be published. Required fields are marked *