I was practicing python and found the below behaviour and I failed to understand why. Can someone explain why?
Case 1
a = [[] for i in range(5)]
b = [[]] * 5
a[3].append(3)
b[3].append(3)
print(a) # Output: [[], [], [], [3], []]
print(b) # Output: [[3], [3], [3], [3], [3]]
I see different behavior on a and b, what's the difference between a and b?
Case 2
def test(sentences):
root = {}
for sentence in sentences:
base = root
for word in sentence.split(' '):
if not base.get(word):
base[word] = {}
base = base[word]
return root
print(test(["Hello world", "Hello there"]))
# Output: {'Hello': {'world': {}, 'there': {}}}
Maybe a noob question but In Case 2 when you're not modifying root how is it getting modified?