[ACCEPTED]-Applying a method with no return value to each element of a list-list-comprehension

Accepted answer
Score: 13

No - list comprehensions are meant to be 18 use with functions having return values. It's 17 how their semantics are defined:

List comprehensions 16 provide a concise way to create lists 15 without resorting to use of map(), filter() and/or lambda. The 14 resulting list definition tends often 13 to be clearer than lists built using those 12 constructs. Each list comprehension consists 11 of an expression followed by a for clause, then 10 zero or more for or if clauses. The result 9 will be a list resulting from evaluating 8 the expression in the context of the for 7 and if clauses which follow it.

Having 6 read this, it should be clear that "a 5 list comprehension from a function having 4 no return value" is an oxymoron.

Just 3 use a for loop for something "one off":

import random
L = []
for x in range(5):
  l = range(5)

Clean 2 and simple. Your shuffled function is also just 1 fine, and can be used in a list comprehension.

Score: 8

Eli is quite right. But I'd go for something 1 more concise:

import random

L = [range(5) for each in xrange(5)]
for each in L:


OTOH you could use random.sample():

from random import sample

xr = xrange(5)
L = [sample(xr, 5) for each in xr]

More Related questions