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?
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]]
the return value of extend
is None
.
list.extend()
extends a list in place. Python standard library methods that alter objects in-place always return None
(the default); your list comprehension executed a.extend()
twice and thus the resulting list consists of two None
return values.
Your a.extend()
calls otherwise worked just fine; if you were to print a
it would show:
[1, 2, 3, 4, 3, 4]
You don't see the None
return value in the Python interpreter, because the interpreter never echoes None
results. You could test for that explicitly:
>>> a = []
>>> a.extend(['foo', 'bar']) is None
True
>>> a
['foo', 'bar']
extend
function extends the list with the value you've provided in-place and returns None
. That's why you have two None
values in your list. I propose you rewrite your comprehension like so:
a = [1, 2]
b = [3, 4]
m = [a + [v] for v in b] # m is [[1,2,3],[1,2,4]]
For python lists, methods that change the list work in place and return None
. This applies to extend
as well as to append
, remove
, insert
, ...
In reply to an older question, I sketched an subclass of list
that would behave as you expected list
to work.
Why does [].append() not work in python?
This is intended as educational. For pros and cons.. look at the comments to my answer.
I like this for the ability of chaining methods and working in a fluent style, e.g. then something like
li = FluentList()
li.extend([1,4,6]).remove(4).append(7).insert(1,10).reverse().sort(key=lambda x:x%2)
would be possible.
a.extend()
returns None
.
You probably want one of these:
>>> m = a + b
>>> m
[1, 2, 3, 4]
>>> a.extend(b)
>>> a
[1, 2, 3, 4]
Aside from that, if you want to iterate over all elements of a list, you just can do it like that:
m = [somefunction(element) for element in somelist]
or
for element in somelist:
do_some_thing(element)
In most cases there is no need to go over the indices.
And if you want to add just one element to a list, you should use somelist.append(element)
instead of `somelist.extend([element])
来源:https://stackoverflow.com/questions/20094511/python-list-comprehension-and-extend