A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing


  • 5 years ago

Strictly python question. Variable names point to objects, they don't contain them - I get that. I am having trouble understanding what is going on with this: def test(a=[]): a.append(1) return a The variable 'a' gets assigned to the same list object each time the function is called, so each time the list object gets mutated. What I don't get is - where is this object? - why does it persist ? - how does python always assign a to the same object? tia

  • This Question is Closed
  1. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    You've defined a function test that takes an argument a. If no argument is passed to the function when it is called it will use the default you've specified. In creating the function, you created a list object [ ] for the function to use as its default. The list is part of the function. It persists because there is some other object with a reference to it. In this case the object which is keeping a reference to this list is the function itself. The dir function may help give some insight. It takes an object and returns a list of strings where each string in that list is the name of an attribute of the object. class Foo: def __init__(self,a): self.bar = a f = Foo('stuff') print dir(f) print f.bar The above code shows how dir works. From that info you can take a look at this small example taken from your function test. http://dpaste.com/519173/

  2. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    Thank you very much for that answer and the dir function. I never even considered that the function was keeping ahold of it and I was going crazy cause it didn't show up in globals() or locals() (from the shell).

  3. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...


  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.