Appending item to lists within a list comprehension

ariel picture ariel · Mar 24, 2010 · Viewed 57.5k times · Source

I have a list, let's say, a = [[1,2],[3,4],[5,6]]

I want to add the string 'a' to each item in the list a.

When I use:

a = [x.append('a') for x in a] 

it returns [None,None,None].

But if I use:

a1 = [x.append('a') for x in a]

then it does something odd.

a, but not a1 is [[1,2,'a'],[3,4,'a'],[5,6,'a']].

I don't understand why the first call returns [None, None, None] nor why the second changes on a instead of a1.

Answer

Mike Graham picture Mike Graham · Mar 24, 2010

list.append mutates the list itself and returns None. List comprehensions are for storing the result, which isn't what you want in this case if you want to just change the original lists.

>>> x = [[1, 2], [3, 4], [5, 6]]
>>> for sublist in x:
...     sublist.append('a')
...
>>> x
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]