python list comprehension and extend()

丶灬走出姿态 提交于 2019-12-06 02:00:00

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]]
Thorsten Kranz

For python lists, methods that change the list work in place and return None. This applies to extendas 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])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!