1

I was wondering whether there is more pythonic way or even if it's acceptable to do it this way.

I want to call to some method inside list comprehension, although i don't need any value to be returned, it's just a setter.

Code:

def do_logic(self):
        [self.set_key(j) for i in xrange(2, CONSTANT) if self.lis[i] != 1 for j in xrange(i*2, CONSTANT, i)]

In my eyes it doesn't seem like the right way to it, any suggestions?

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • 3
    Wait, so you're not actually using the list? Just use a for loop. – Morgan Thrapp Jun 28 '16 at 20:36
  • For loop is faster. Perhaps more pythonic would be a **map**. – Prune Jun 28 '16 at 20:36
  • 3
    @Prune map is *the worst*. Because if you tried to run the code in python3 it wouldn't even perform the calls since in python3 map is lazy. In any case both calling `map` or a list-comprehension are **expressions** and expressions should be as side-effect free as possible, their purpose is *to return a value*. So if you don't have a value to return you should just use the plain statements: i.e. explicit `for`. – Bakuriu Jun 28 '16 at 20:37
  • @Bakuriu. On second thought, I quite agree. Thanks for the correction. I was in brainstorming mode, rather than solution mode. – Prune Jun 28 '16 at 20:42

1 Answers1

3

If you don't need the list, don't use a list comprehension. Just use a loop.

mgilson
  • 300,191
  • 65
  • 633
  • 696