1. Mutable default argument
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
print(add_item(3))
Output:
[1]
[1,2]
[1, 2, 3]
Why:
In Python items = [] works like global variable due to the mutability.
Like this:
default_items = []def add_item(item, items=default_items):
items.append(item)
return items
2.is vs ==
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
Output:
True
False
Why:
= = compares the values, and is compares for objects. a and b are not the same object.a = [1, 2, 3]
b = b
print(a == b)
print(a is b)Then Output is:
True
True
3. List multiplication
x = [[0] * 3] * 3
x[0][0] = 99
x[0][1] = 100
print(x)
Output:
[[99,100,0][99,100,0],[99,100,0]]How it works:
It similar to:
x = [[0, 0, 0], [0,0,0],[0,0,0]]it refers the same first object. x[0] is x[1] is x[2]
x[0][1] = 99
x[1][1] = 89
x[2][1] = 30
print(x) –> [[0, 0, 30], [0, 0, 30], [0, 0, 30]]x[0][0] = 99
x[1][2] = 89
x[2][1] = 30print(x) –> [[99, 30, 89], [99, 30, 89], [99, 30, 89]]
*on a list repeats references; it does not create independent copies of nested mutable objects.If you do not need references, use below:
y = [[0] * 3 for _ in range(3)]
y[0][0] = 99
y[0][1] = 66
y[1][2] = 89
y[2][1] = 30print(y) –> [[99, 66, 0], [0, 0, 89], [0, 30, 0]]
4. Loop variable
for i in range(5):
pass
print(i)
Output:
4
5. else with a for loop
for i in range(5):
if i == 3:
break
else:
print("Completed")
print("Finished")
Output:
Finished
Why:
Completed only prints if loops continued without a interrupts.
If no break, then system prints the “completed” as well
7. Function Scope
x = 10
y = [10,20]
def test():
x = 20
y[0] = 30
y[50] = 50
print(x)
print(y)
test()
print(x)
print(y)
Output:
20
[30, 50]
10
[30, 50]
Why:
x = 20 works like a local variable. Not like list, dictionary kind of mutable.If need to update it globaly change the function as:
def test():
global x
x = 20
print(x)
12. Shallow copy
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
print(a)
print(b)
OUTPUT:
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]]Why Copy works differently:
b = a.copy()
Python creates a new outer list, but the inner lists are still shared:That mean, a, and b seperate objects, but innper part are the same as same object referance. We are calling this Shallow copy
a is b –> false
a[0] is b[0] –> True