Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Say i have a function named J and an array named f.

now i call this code:

result = []
for n in f:
    results.append(J(n))

is there any more efficient way of doing this? I was thinking something along the lines of...

results = (J(n) for n in f)

But that didn't work.

share|improve this question
Doesn't Python have a map function? – Peter Taylor Aug 20 '12 at 18:02
3  
I'm afraid that you have misunderstood what we do here. All question are supposed to pose a programming challenge (with an objective winning criterion, natch) so that other programmers can amuse themselves by competing (or by reading other people's entries). General programming question go to Stack Overflow, and we have made special allowance for "tips" questions (and there is already one for python). – dmckee Aug 20 '12 at 22:59

closed as off topic by dmckee Aug 20 '12 at 22:59

Questions on Programming Puzzles & Code Golf Stack Exchange are expected to relate to programming puzzle or code golf within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

2 Answers

up vote 2 down vote accepted
r=map(J,f)

is probably the shortest you can get (although it's unclear what you want here; the example you give works, it just creates a generator instead of a list. Use [], not () for a list comprehension.

share|improve this answer

If n and(/or) f are mutable and J can be altered then you could run just for n in f: J(n). If that isn't possible then your original idea should be the most efficient computation-wise. Map does the same in fewer letters making it more efficient golf-wise.

share|improve this answer

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