views:

158

answers:

4

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

I want to add to each item in a the char '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.

+6  A: 

For the first case, the reason it returns [None, None, None] is because the list.append function returns None, and that's what it stores in the list.

In the second case, it's because the list is mutable, and each time you append the value, the original list is modified.

What you need is a non-in-place append operator, such as +. i.e. [x + ['a'] for x in a].

sykora
+12  A: 

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']]
Mike Graham
+1  A: 

(This is a combination of the answers by Mike Graham and sykora):

If you merely want to change the values in-place, try a regular for-loop, and not a list comprehension:

for sublist in a:
    sublist.append('a')

If you want to leave a alone, and put the result in a1:

a1 = [sublist + ['a'] for sublist in a]

As they explained, append modifies the list, but returns None, while + leaves the list alone, but returns a new, appended list.

Oddthinking
That should be a1 = [sublist + ['a'] for sublist in a]. Note brackets around 'a'.
PreludeAndFugue
Whoops. Fixed. Thanks.
Oddthinking
A: 

leave the a = and use the side effect on a:

[x.append('a') for x in a] 
print a
wiso
Please, no. Throwing away a list comprehension just to utilize its side effects is bad form; your suggestion works, but it's frowned upon just like similar `map` usage has been frowned upon. Explicit is better than implicit; use a loop rather than a list comprehension.
ΤΖΩΤΖΙΟΥ