Can this be done with list comprehension?
Gary Herron
gherron at islandtraining.com
Sat Jun 7 18:44:16 EDT 2008
Karlo Lozovina wrote:
> This is what I'm trying to do (create a list using list comprehesion, then
> insert new element at the beginning of that list):
>
> result = [someFunction(i) for i in some_list].insert(0, 'something')
>
> But instead of expected results, I get None as `result`. If instead of
> calling `insert` method I try to index the list like this:
>
> result = [someFunction(i) for i in some_list][0]
>
> It works as expected. Am I doing something wrong, or I can't call list
> methods when doing list comprehension?
>
The problem is that list methods like insert do not return a list --
they modify it in place. If you do
a = [1,2,3]
a.insert(0, 'something')
then a will have the results you expect, but if you do
b = a.insert(0,'something')
you will find b to be None (although a will have the expected list).
> P.S.
> In case you're wondering, it has to be done in one line ;).
>
>
>
More information about the Python-list
mailing list