Rohan S Byrne
Rohan S Byrne

Reputation: 100

Pythonic one-liner to populate a sequence

Say I want to calculate the first n Fibonacci numbers and put them into a list. With a 'for' loop, this is trivial. But is there a one-liner - a kind of list comprehension magic, perhaps - that could achieve this more elegantly?

I asked this question previously but it was shut down on the premise that it had already been answered. But neither of the suggested answers were actually answers to this particular question! They were of this form:

fib = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]

Which yields the nth member of the sequence. I'm looking for a Pythonic one-line expression that outputs a complete sequence, i.e. not '3' but [1, 1, 2, 3, 5, ...]

I'd like to reiterate that this isn't a problem I need a solution for. A simple 'for' loop does the job just fine. What I'm wondering is whether there's a preferred way of doing something like this in one line. This is not a 'code golf' question - it is not for curiosity's sake - it's about adding a new tool to the toolkit and deepening my understanding of the Pythonic idiom.

Thanks!

Upvotes: 1

Views: 75

Answers (2)

Vishal Singh
Vishal Singh

Reputation: 6234

This will calculate the first n Fibonacci numbers.

n = 10
fibs = reduce(lambda x, _: x + [x[-2] + x[-1]], [0] * (n - 2), [0, 1])

Upvotes: 2

nog642
nog642

Reputation: 621

You can just take the one liner you have already found to get an arbitrary element:

>>> fib = lambda n: reduce(lambda x, _: [x[1], x[0] + x[1]], range(n), [0, 1])[0]
>>> fib(6)
8

And use it to fill a list with a list comprehension:

>>> [reduce(lambda x, _: [x[1], x[0] + x[1]], range(n), [0, 1])[0] for n in range(10)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Upvotes: 0

Related Questions