python objects

Handout 3 – Objects

Key Associations

Variables and Lookup Tables

Associate these words together:

Example Statement:
"Assigning a variable changes the value of the variable in the lookup table."

Objects and Memory

Associate these words together:

Example Statement:
"Modifying an object changes the actual object in the heap."


Lookup Table Structure

The lookup table has two columns:

  1. Variable Name
  2. Variable Value

Types of Variable Values:

Example:

x = 5  # x is assigned a primitive value (integer 5)
y = "hello"  # y is assigned a reference to a string object in the heap

Aliasing in Python

Aliasing occurs when multiple variables point to the same object.
Example: Lists (Manual Aliasing)

a = [1, 2, 3]  # a points to a list object
b = a  # b now points to the same list object
c = a  # c also points to the same list
d = b  # d also points to the same list

Effect: If a is modified (e.g., using append()), the changes will reflect in b, c, and d.
Example: Strings (Automatic Aliasing)

a = "hello"
b = "hello"
c = "hello"
d = "hello"

Observation: Python automatically aliases identical string values, meaning all four variables have the same object ID.
Scope in Python

Scope refers to the current frame in the stack diagram.
Local vs Global Scope:

    Local Scope: Variables inside a function exist only within that function.
    Global Scope: Variables outside functions exist throughout the program.

Important Note:

Even if a variable inside a function is local, it may point to the same object as a global variable. If the object is modified, the global variable will reflect the change.
Review Tip:

Make sure to review Problem 3 from Lab 7. Analyze:

    Subtle function changes
    Whether a statement is an assignment (changes a variable) or a modification (changes an object)

Suggested Practice:
Draw stack diagrams to visualize variable assignments and references.

------





# **Day 4: List Basics**

## **Notes:**
This section covers the basics of lists. We'll cover them in more detail after we cover objects and references.

We've used variables to store basic information such as numbers, strings, and boolean values. We can also store more complex information. A **list** stores a sequence of elements `[x1, x2, x3, ...]`.  
- **Order matters:** `[x1, x2] != [x2, x1]`
- You can store different types of variables in the same list: `[1, 3, "test", True]`.  
- You can even store lists in lists! _(Note: For now, don't store lists in lists! You'll understand why when we talk about objects and mutability.)_

### **Quick Review:**
- You can create a list using square brackets: `[1,2,5,1,3,"test"]`.
- To read an element from `some_list`, use `some_list[index]`.  
  _(The first element is at position **0**.)_

#### **Example:**
```python
print "X",
print "X",

Output:

XX

List Functions:

    The built-in function len(x) finds the length of any list.
    You can add something to the end of a list using .append().

Problem 12 {alone}:

What is the output of the following code?
(The output of each program has at most two semicolons.)
Example 1:

some_list = [1,2,3,4]
some_list.append(5)
print some_list

Output:

[1,2,3,4,5]

Example 2:

some_list = [3,6,2,5]
i = 1
while i < 3:
    print some_list[i], ";"
    i = i + 1
print some_list[3]

Day 6: Objects and References
Notes:

Lists are fundamentally different than everything we've seen to date. They are the first example we've seen of an object.

Instead of storing objects in the variable table, Python stores a pointer or reference to the object.
Example:

example_list = []

def append_one(my_list):
    "This is a function that adds something to the end of a list"
    my_list.append(1)

append_one(example_list)
print example_list

Output:

[1]

Understanding References:

    At point 1, example_list is an empty list.
    At point 2, the function append_one receives a reference to example_list.
    At point 3, the function modifies the original list.
    At point 4, example_list contains [1].

Problem 13:

What is the output of the following code? (Use single digits for the output of id(x))
Example:

def small_function(my_list):
    print "in function:"
    print id(my_list)
    my_list.append(1)

example_list = []
example2_list = [3,6]

print id(example_list)
print id(example2_list)

small_function(example_list)

Output:

18162752
12860152
in function:
18162752

Day 6: Mutability
Notes:

Lists are mutable objects. Mutability means that the object can be changed.
Example:

list1 = [1,2,4]
list2 = list1
list2.append(3)
print list1

Output:

[1,2,4,3]

Explanation:
Since list2 is just a reference to list1, changing list2 also changes list1.
Problem 14:

What is the output of the following code?
Example:

some_list = [1,3,2]

def f1(my_list):
    my_list.append(7)
    print id(my_list), ";"
    return [1,4,5]

print id(some_list), ";"
some_list.append(5)
print id(some_list), ";"
some_list = [4,3,7]
print id(some_list), ";"
some_list = f1(some_list)
print id(some_list)

Day 6: Member Functions
Notes:

Lists have member functions that modify the list itself.
Common Member Functions:

    append(element): Adds element to the end of the list.
    insert(index, element): Inserts element before index.
    reverse(): Reverses the order of elements in the list.
    remove(element): Removes the first instance of element.

Non-Modifying Functions:

    index(element): Returns the position of element.
    count(element): Returns the number of times element appears.

Day 4: Lists Redux
Notes:
Key Takeaways:

    Lists are mutable. When you modify a list, all references to it see the change.
    Lists have member functions. Many of these functions modify the list itself.

Other List Features:

    Change elements with example_list[i] = 5.
    Delete elements with del example_list[i].
    Use len(x) to find the length of a list.
    Check membership with:

    3 in [3,5,7]   # Returns True
    6 in [3,4,1]   # Returns False

Problem 15:

Write a function that shifts the first element of a list to the end.
Function Definition:

def shift(my_list):
    "Shifts the list [x1,x2,...,xn] to [x2,x3,...,xn,x1]."
    my_list.append(my_list.pop(0))

Problem 16:

Write a function that returns the last index of an element in a list.
Function Definition:

def last_index(my_list, element):
    "Returns the position of the last instance of element in my_list"
    return len(my_list) - 1 - my_list[::-1].index(element)

Day 4: Advanced Positioning and Slicing
Notes:

    You can select elements using some_list[i].
    You can also use negative indexes:
        The last element is at some_list[-1].

List Slicing:

some_list[start:end]  # Returns a new list with elements from start to (end-1).

Example:

some_list = [1, 2, 3, 4, 5]
print(some_list[1:4])  # Output: [2, 3, 4]
print(some_list[:3])   # Output: [1, 2, 3]
print(some_list[2:])   # Output: [3, 4, 5]

Quiz

To mark this module as complete, you must finish this quiz. Once submitted, you'll need to wait 2 hours before attempting it again.