I think these are good questions!
Sometimes I like to write out how the variables change as I go through a loop.
Line 1
- things:
[[thingA, 7], [thingB, 0]]
Line 2
- things:
[[thingA, 7], [thingB, 0]]
- thing:
[thingA, 7]
Line 3
- things:
[[thingA, 7], [thingB, 0]]
- thing:
[thingA, 7]
- cost:
7
Line 4
- things:
[[thingA, 7], [thingB, 0]]
- thing:
[thingA, 7]
- cost:
7
Line 6
- things:
[[thingA, 7], [thingB, 0]]
- thing:
[thingA, 7]
- cost:
7
Line 7
- things:
[[thingA, 7, "Costs money"], [thingB, 0]]
- thing:
[thingA, 7, "Costs money"]
- cost:
7
Line 2 (Going through for loop for next item in things. Cost only exists for 1 iteration of the loop)
- things:
[[thingA, 7, "Costs money"], [thingB, 0]]
- thing:
[thingB, 0]
Line 3
- things:
[[thingA, 7, "Costs money"], [thingB, 0]]
- thing:
[thingB, 0]
- cost:
0
Line 4
- things:
[[thingA, 7, "Costs money"], [thingB, 0]]
- thing:
[thingB, 0]
- cost:
0
Line 5
- things:
[[thingA, 7, "Costs money"], [thingB, 0, "No cost"]]
- thing:
[thingB, 0, "No cost"]
- cost:
0
Line 6
- things:
[[thingA, 7, "Costs money"], [thingB, 0, "No cost"]]
- thing:
[thingB, 0, "No cost"]
- cost:
0
Line 8 (Went through all items in for loop. Thing and cost belong to the loop. Since things exists outside the loop the changes are kept.)
- things:
[[thingA, 7, "Costs money"], [thingB, 0, "No cost"]]
Here is how I think about:
Even though we don’t have to write the code this way in the background Python treats the things list like this…
list1 = ["thingA", 7]
list2 = ["thingB", 0]
things = [list1, list2]
In the for loop python isn’t really doing anything to things
since it is a list holding pointers to where other lists are stored.
The other tricky idea is that append mutates (changes) list objects. It is a little different then some other things in Python where you need to reassign values to a variable. I’ll use >>
to indicate output. Like…
x = 1
x + 100
>>101
print(x)
>>1
x += 100
print(x)
>>101
So if you try some code like what is below the lists will change without having to do any variable assignment.
my_list = [1, "cat", ["a", "b"]]
my_list.append("emily")
print(my_list)
>>[1, "cat", ["a", "b"], "emily"]
my_list[2].append("c")
print(my_list)
[1, "cat", ["a", "b", "c"], "emily"]
I hope this helps! If you still have questins I can try again 