When I googled “Fibonacci Python” today, I found a lot of algorithms (most of them easy to understand). But I wondered — is there a Python one-liner to find
The popular Italian mathematician Fibonacci (original name: “Leonardo of Pisa”) introduced in the year 1202 the Fibonacci numbers – with the surprising observation that these numbers occur everywhere in various fields such as math, art, and biology.
What are Fibonacci numbers? The Fibonacci numbers are the numbers of the Fibonacci series. The series starts with the numbers 0 and 1. Each following series element is the sum of the two previous series elements. That’s already the algorithm to calculate the Fibonacci series!
We consider the following problem: Given a number n>2. Calculate a list of the first n Fibonacci numbers in a single line of code (starting from the first Fibonacci number 0)!
# Dependencies from functools import reduce # The Data n = 10 # The One-Liner fibs = reduce(lambda x, _: x + [x[-2] + x[-1]],  * (n-2), [0, 1]) # The Result print(fibs)
Listing: Calculating the Fibonacci series in one line of Python code.
Try it yourself in our interactive code snippet:
Exercise: What’s the output of this code snippet?
How It Works
Let’s start with the reduce function — how does it work? We consider the reduce function with three parameters: reduce(function, iterable, initializer).
“Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is theDocumentation
updatevalue from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation,and serves as a default when the sequence is empty. If initializer is not given and sequencecontains only one item, the first item is returned.”
The reduce function is useful if you want to aggregate state information that is just computed “on the fly”. For example, you compute the new Fibonacci number based on the previous two Fibonacci numbers that have just been computed. This is difficult to achieve with list comprehension (see Chapter 3) because you cannot (with standard means) access the newly created values from the list comprehension.
In the puzzle, we use the reduce function reduce(function, iterable, initializer). with the idea of consecutively adding the new Fibonacci number to an aggregator object that incorporates one value at a time from the iterable object as specified by the function. Here, we use a simple list as aggregator object with the two initial Fibonacci numbers [0, 1]. Recap that the aggregator object is handed as first argument to the function (in our example x). The second argument is the next element from the iterable. However, we initialized the iterable with (n-2) dummy values – simply to force the reduce function to execute function (n-2) times. Therefore, we use the throw-away parameter “_” to indicate that we are not really interested in it. Instead, we simply append the new Fibonacci number to the aggregator list x, calculated as the sum of the previous two Fibonacci numbers.
In summary, you’ve improved your understanding of another important pattern for Python one-liners: using the reduce function to create a list that dynamically uses the freshly updated or added list elements to compute new list elements. You will find this useful pattern quite often in practice.
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.