1

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)

The hash.get(key, []) returns a [] and I was expecting that dictionary would be {'a': ['A']}. However the dictionary is set as {'a': None}. On looking this up further, I realised that this was occurring due to python lists.

list_variable = []
list_variable.append(val)

sets the list_variable as ['A'] However, setting a list in the initial declaration

list_variable = [].append(val)
type(list_variable)
<type 'NoneType'> 

What is wrong with my understanding and expectation that list_variable should contain ['A'] Why are the statements behaving differently?

2
  • 1
    Avoid using list as a variable name, it shadows the built-in list() method. Commented Jun 5, 2013 at 9:04
  • The problem occurred originally in the first code segment and there wasn't any variable name that can shadow the built in methods. Anyway, let me correct the question. Commented Jun 5, 2013 at 9:18

2 Answers 2

6

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.