Ryan Saxe
Ryan Saxe

Reputation: 17869

Python list comprehension on class

take the following class:

class Foo:
    def __init__(self,boolean):
        bar = boolean

and let foos be a list of instances of Foo

I want to do the following in a list comprehension:

hold = []
for foo in foos:
    foo.added = "I was added in iteration"
    if foo.bar:
        hold.append(some_function(foo.bar))
    else:
        hold.append(some_other_function(foo.bar))

note: this is not actually how it looks, I just needed to make an if and else

So without the foo.added line, this is my solution:

[some_function(foo.bar) if foo.bar else some_other_function(foo.bar) for foo in foos]

How can I also add an attribute in a list comprehension?

reason for this:

The code that I am running will be accessed so frequently that every fragment of a second of processing counts here. A list comprehension avoids the append line, and given the amount this is called, that could be very helpful

Upvotes: 1

Views: 1459

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

Just for learning purpose, never use this is in real code. A normal loop is a far better choice here:

[some_function() if foo.bar else some_other_function() 
         for foo in foos if not setattr(foo, 'added',  "I was added in iteration")]

Upvotes: 4

Related Questions