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)
Rob123
  • 895
  • 6
  • 10
  • You can but you shouldn't. https://twitter.com/raymondh/status/902658204345049088 – Moses Koledoye Aug 31 '17 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. – Christian Dean Aug 31 '17 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 '17 at 12:01

1 Answers1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I get what you mean. Instead just keep it a for loop, perhaps with it just on one line. Thanks – Rob123 Aug 31 '17 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 '17 at 12:19