I was wondering what is the difference between this two code examples. The first one doesn’t work(Key error) but the second one works perfectly. I was using the append function and somehow it didn’t work for me. Can someone explain why is it. Thank you!
- First one (with key error)
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
map = dict()
for i, j in enumerate(nums):
map[i].append(j) #adding the element using append function
return(map)
Traceback (most recent call last):
File "C:\Users\Larionova\Desktop\containsNearbyDuplicate.py", line 14, in
s1 = Solution().containsNearbyDuplicate(list1, 3)
File "C:\Users\Larionova\Desktop\containsNearbyDuplicate.py", line 11, in containsNearbyDuplicate
map[i].append(j)
KeyError: 0
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
map = dict()
for i, j in enumerate(nums):
map[i] = j
return(map)
>Solution :
map[i].append(j) assumes that map[i] already holds a list.
map[i] = j just sets (or overrides) the value of map[i].