0

I know that for creating lists you can shorten a few lines down to something like (in python):

a = [k*2 for k in range(10)]

Can you do this for when sending data through a pipe. (using multiprocessing module in this case). eg:

k = 'hello'
[channel.send(k) for channel in channels]

instead of:

k = 'hello'
for channel in channels:
    channel.send(k)

Any suggestions would be great! Thanks in advance.

EDIT: Has been answered. List comprehensions bad idea. Just keep it neat to one line:

k = 'hello'
for channel in channels: channel.send(k)
3
  • You can but you shouldn't. twitter.com/raymondh/status/902658204345049088 Aug 31, 2017 at 11:59
  • 2
    In this case no, you shouldn't use a list comprehension. They should only be used when you are trying to build a list of values. If you simply need to iterate over an iterable, use a normal for loop. Aug 31, 2017 at 11:59
  • 1
    Besides, your two examples have the exact same length; the list comprehension replaces the : and the newline with a [ and ]. In fact, you can write the for loop on one line, in which case the list comprehension is longer, in addition to less efficient.
    – chepner
    Aug 31, 2017 at 12:01

1 Answer 1

2

No. List comprehensions are for creating lists. If you don't want the list, don't use a list comprehension. There is nothing wrong with using a for loop when it is the appropriate thing to use.

2
  • I get what you mean. Instead just keep it a for loop, perhaps with it just on one line. Thanks
    – Rob123
    Aug 31, 2017 at 12:10
  • 1
    I wouldn't even put it on one line. The line break provides an immediate, clear distinction between what is being iterated over and what is being done with each of the iterated objects. Saving one line of code accomplishes nothing meaningful.
    – chepner
    Aug 31, 2017 at 12:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.