Pass by value or by reference

What a function really receives: a copy or access to the caller's data. Aliases, side effects on a list passed as a parameter, mutable and immutable types, input and output parameters.

  • 25 cards
  • 7 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand
  6. Line by line
  7. Step by step

A few cards from the deck

  • Pass by value: what is it?

    Show the answer

    A way of passing arguments where the function receives a copy of the argument: changing the parameter changes nothing for the caller.

    This is how C works: for a function to change a variable of the caller, you pass it the variable's address.

  • What does this program print?

    ```python
    def add_one(n):
    n = n + 1
    return n

    x = 5
    y = add_one(x)
    print(x, y)
    `

    • 5 6
    • 6 6
    • 5 5
    • 6 5
    Show the answer

    5 6

    n = n + 1 makes the local name n refer to a new integer, 6: x still refers to 5. Only the returned value, stored in y, leaves the function.

  • An … parameter is only read by the function; an … parameter lets it pass a result to the caller; an input-output parameter is read then modified.

    Show the answer

    An input parameter is only read by the function; an output parameter lets it pass a result to the caller; an input-output parameter is read then modified.

    In Python, a list passed to a function that sorts it in place is an input-output parameter; an integer can only be an input, and the result comes back through return.