I'm wrong or Will we fix the ducks limp?

Matt Wheeler m at funkyhat.org
Fri Jun 3 11:54:39 EDT 2016


Hi,

On Fri, 3 Jun 2016, 16:04 Sayth Renshaw, <flebber.crue at gmail.com> wrote:

>
> So at the point I create the variable it refers to an object.
>

It's best to think of them as names, rather than variables, as names in
python don't behave quite how you'll expect variables to if you're coming
from some other languages.

More correctly when I create the variable and assign a list action to the
> variable I believe I should be creating a reference to a list object in one
> motion; however python would like me to create the object first before
> creating a reference to it, is that the catch?
>

I'm not 100% sure what you mean by "assign a list action to the variable".

`[]` is an empty list literal. Putting that in your code will create a new
empty list object every time it's reached.
`name =` assigns a new name which refers to the thing to the right of it.

My best guess as to the source of your confusion is that you're not seeing
the list as an object (let me know if I'm wrong).
A list is an object just the same as the items you want to put in it, it's
just a different type, it's not special syntax built into the language.
That means you need to create one if you want it to be there.

I am not allowed to create references to an object at the same time I
> create the object is that correct?
>

That's exactly what `name = []` is doing (see above).

> Assuming the answer is going to be that some methods apply to multiple
types if not then what is happening?
[from your first email]

If you want to see it like this that might help. Any number of classes and
not just the builtin list is likely to have an append method.
Even if that were not true, expecting name.append() in a context where name
doesn't exist to somehow magically create a list object for you, assign a
name to it and then call the method you asked for would involve quite a few
leaps of logic, faith or something.

Consider a situation where you actually intended to create an instance of a
different type which also has an `.append()` method, but somehow that went
wrong (you spelt the name incorrectly, perhaps), which is preferable:

Magic list creation mode:
>>> name = OtherClassWithAppendMethod()
>>> naem.append('this')
Great. Now we have our desired OtherClassWithAppendMethod instance, which
is empty, and a useless list which contains the stuff that should have been
given to `name`.
No errors, just a bug that's really really fun to track down.

Regular boring Python:
>>> name = OtherClassWithAppendMethod()
>>> naem.append('this')
NameError: name 'naem' is not defined

>


More information about the Python-list mailing list