Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply function to elements of a list?

I want to apply a function to all elements in the list, but I want to actually change the elements (which are objects), not view results. I think this is the problem with using map() or list comprehensions.

class Thing(object):
    pass

# some collection of things
my_things

# they are all big...

# produces SyntaxError: invalid syntax
[i.size = "big" for i in my_things]

# produces SyntaxError: lambda cannot contain assignment
map(lambda i: i.size="big", [i for i in my_things]) 

# no error, but is it the preferred way?
for i in my_things:
    i.size="big"

What is the way to do this?

like image 863
cammil Avatar asked May 11 '12 15:05

cammil


2 Answers

And what's wrong with

for i in my_things:
    i.size = "big"

You don't want to use neither map nor list comprehansion because they actually create new lists. And you don't need that overhead, do you?

like image 182
freakish Avatar answered Oct 11 '22 00:10

freakish


You could use the __setattr__ method to assign the attribute in a list comprehension. Although, according to some SO threads, using list comprehensions without using the output is not pythonic.

[i.__setattr__('size', 'big') for i in my_things]
like image 45
garnertb Avatar answered Oct 11 '22 01:10

garnertb