Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension and extend()

Working my way into Python (2.7.1) But failing to make sense (for hours) of this:

>>> a = [1, 2]
>>> b = [3, 4]
>>> 
>>> a.extend([b[0]])
>>> a
[1, 2, 3]
>>> 
>>> a.extend([b[1]])
>>> a
[1, 2, 3, 4]
>>> 
>>> m = [a.extend([b[i]]) for i in range(len(b))] # list of lists
>>> m
[None, None]

The first two extends work as expected, but when compacting the same in a list comprehension it fails. What am i doing wrong?

like image 483
user3012707 Avatar asked Nov 20 '13 11:11

user3012707


1 Answers

extend modifies the list in-place.

>>> [a + b[0:i] for i in range(len(b)+1)]
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
like image 114
Vlad Avatar answered Oct 31 '22 21:10

Vlad