Skip to content Skip to sidebar Skip to footer

Appending An Item To A Python List In The Declaration Statement List = [].append(val) Is A Nonetype

I am running into this situation while using chained methods in python. Suppose, I have the following code hash = {} key = 'a' val = 'A' hash[key] = hash.get(key, []).append(val)

Solution 1:

The .append() function alters the list in place and thus always returns None. This is normal and expected behaviour. You do not need to have a return value as the list itself has already been updated.

Use the dict.setdefault() method to set a default empty list object:

>>>hash = {}>>>hash.setdefault('a', []).append('A')>>>hash
{'a': ['A']}

You may also be interested in the collections.defaultdict class:

>>> from collections import defaultdict
>>> hash = defaultdict(list)
>>> hash['a'].append('A')
>>> hash
defaultdict(<type'list'>, {'a': ['A']})

If you want to return a new list with the extra item added, use concatenation:

lst = lst + ['val']

Solution 2:

append operates in-place. However you can utilize setdefault in this case:

hash.setdefault(key, []).append(val)

Post a Comment for "Appending An Item To A Python List In The Declaration Statement List = [].append(val) Is A Nonetype"