[Tutor] Wrapping with list

Steven D'Aprano steve at pearwood.info
Fri Sep 13 13:25:42 CEST 2013


On Fri, Sep 13, 2013 at 12:24:40PM +0200, Dotan Cohen wrote:
> A function that I wrote works on a list or on a string. If the
> function is passed a string, then it wraps the string in a list at the
> top of the function. Is it bad form to wrap the sting in place?
> 
> if not isinstance(someVar, list):
>     someVar = [someVar]
> 
> To avoid that, I am creating a list then appending the original value:
> 
> if not isinstance(someVar, list):
>     temp = someVar
>     someVar = []
>     someVar.append(temp)
> 
> Is my prudence unwarrented?

Yes :-)

The two pieces of code end up having *exactly* the same effect, except 
the second takes three lines instead of one, is harder to understand, 
and is a tiny bit slower. Oh, and it introduces an extra variable, which 
otherwise has no real reason to exist.

In fact, it's quite likely that under the hood, the first version 
someVar = [someVar] ends up doing precisely what the second version 
does, except in fast C code rather than slower Python code.



-- 
Steven


More information about the Tutor mailing list