Kvass
Kvass

Reputation: 8434

Python - generate array of returns from function that changes its return value

What is a good pythonic way to generate an array of results from multiple function calls with a function that changes what it returns after each call? For example, say I have a function foo that returns 'callno-X' each time it is called, and X is increased by 1 every time. I want to then be able to say something like bar(5) that will call foo() five times and gather the results in an array, returning ['callno-1','callno-2','callno-3','callno-4','callno-5']. Is there any good way to do this?

Upvotes: 2

Views: 64

Answers (2)

user2555451
user2555451

Reputation:

How about this:

map(foo, xrange(5))

It's short and simple.

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251353

Just use a list comprehension:

returnValues = [foo() for x in xrange(5)]

Upvotes: 6

Related Questions