{"id":1165,"date":"2020-11-16T03:40:53","date_gmt":"2020-11-16T03:40:53","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1165"},"modified":"2025-03-27T14:58:28","modified_gmt":"2025-03-27T14:58:28","slug":"python-fibonacci-sequence","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/advanced-python\/python-fibonacci-sequence\/","title":{"rendered":"Python Fibonacci Sequence"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to define a custom Sequence type in Python and how to implement the Fibonacci sequence using a custom Sequence type.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-custom-sequence-type-in-python'>Introduction to the custom Sequence type in Python <a href=\"#introduction-to-the-custom-sequence-type-in-python\" class=\"anchor\" id=\"introduction-to-the-custom-sequence-type-in-python\" title=\"Anchor for Introduction to the custom Sequence type in Python\">#<\/a><\/h2>\n\n\n\n<p>Sometimes, it&#8217;s useful to implement a custom <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-sequences\/\">sequence type<\/a> that has functions similar to the built-in sequence type like <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-tuples\/\">tuples<\/a> and <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-list\/\">lists<\/a>.<\/p>\n\n\n\n<p>As you&#8217;ve learned so far, a sequence can be <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-mutable-and-immutable\/\">mutable or immutable<\/a>. In this tutorial, you&#8217;ll focus on defining a custom immutable sequence type.<\/p>\n\n\n\n<p>Basically, an immutable sequence type should support two main functions:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Return the number of elements of the sequence. Technically, this requirement is not necessary.<\/li>\n\n\n\n<li>Return an element at a given index or raise an <code>IndexError<\/code> if the index is out of bounds.<\/li>\n<\/ul>\n\n\n\n<p>If an object can fullfil the above requirements, then you can:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the square brackets <code>[]<\/code> syntax to retrieve an element by an index.<\/li>\n\n\n\n<li>Iterate over the elements of the sequence using the for loop, comprehension, etc.<\/li>\n<\/ul>\n\n\n\n<p>Technically, a custom sequence type needs to implement the following methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>__getitem__<\/code> &#8211; returns an element at a given index.<\/li>\n\n\n\n<li><code>__len__<\/code> &#8211; returns the length of the sequence.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='the-__getitem__-method'>The __getitem__ method <a href=\"#the-__getitem__-method\" class=\"anchor\" id=\"the-__getitem__-method\" title=\"Anchor for The __getitem__ method\">#<\/a><\/h3>\n\n\n\n<p>The <code>__getitem__<\/code> method has the <code>index<\/code> argument which is an integer. The <code>___getitem__<\/code> should return an element from the sequence based on the specified <code>index<\/code>.<\/p>\n\n\n\n<p>The range of the <code>index<\/code> should be from <code>zero<\/code> to <code>length - 1<\/code>. If the <code>index<\/code> is out of bounds, the <code>__getitem__<\/code> method should raise an <code>IndexError<\/code> exception.<\/p>\n\n\n\n<p>Also, the <code>__getitem__<\/code> method can accept a slice object to support slicing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='the-__len__-method'>The __len__ method <a href=\"#the-__len__-method\" class=\"anchor\" id=\"the-__len__-method\" title=\"Anchor for The __len__ method\">#<\/a><\/h3>\n\n\n\n<p>If a custom sequence has the <code>__len__<\/code> method, you can use the built-in <code>len<\/code> function to get the number of elements from the sequence.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-fibonacci-sequence'>Introduction to the Fibonacci sequence <a href=\"#introduction-to-the-fibonacci-sequence\" class=\"anchor\" id=\"introduction-to-the-fibonacci-sequence\" title=\"Anchor for Introduction to the Fibonacci sequence\">#<\/a><\/h2>\n\n\n\n<p>The Fibonacci sequence was first discovered by Leonardo Fibonacci, who is an Italian mathematician, around A.D. 1170.<\/p>\n\n\n\n<p>In the Fibonacci sequence, each number is the sum of two numbers that precede it. For example:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">1, 1, 2, 3, 5, 8 , 13, 21, ...<\/code><\/span><\/pre>\n\n\n<p>The following formula describes the Fibonacci sequence:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">f(1) = 1\nf(2) = 1\nf(n) = f(n-1) + f(n-2) if n &gt; 2<\/code><\/span><\/pre>\n\n\n<p>Some sources state that the Fibonacci sequence starts at zero, not 1 like this:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">0, 1, 1, 2, 3, 5, 8 , 13, 21, ...<\/code><\/span><\/pre>\n\n\n<p>But we&#8217;ll stick with the original Fibonacci sequence that starts at one.<\/p>\n\n\n\n<p>To calculate a Fibonacci number in Python, you define a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-recursive-functions\/\">recursive function<\/a> as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> fib(n<span class=\"hljs-number\">-2<\/span>) + fib(n<span class=\"hljs-number\">-1<\/span>) <\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this recursive function, the <code>fib(1)<\/code> and <code>fib(2)<\/code> always returns 1. And when n is greater than 2, the fib(n) = fib(n-2) &#8211; fib(n-1)<\/p>\n\n\n\n<p>The following adds a statement at the beginning of the <code>fib<\/code> function for the logging debugging purpose:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Calculate Fibonacci of <span class=\"hljs-subst\">{n}<\/span>'<\/span>)\n    <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> fib(n<span class=\"hljs-number\">-2<\/span>) + fib(n<span class=\"hljs-number\">-1<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And this shows output of the <code>fib<\/code> function when calculating the Fibonacci of 6:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Calculate the Fibonacci of 6\nCalculate the Fibonacci of 4\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 3\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 5\nCalculate the Fibonacci of 3\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 4\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 3\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1<\/code><\/span><\/pre>\n\n\n<p>The output shows that the <code>fib<\/code> function has many repetitions. For example, it has to calculate the Fibonacci of 3 three times. This is not efficient.<\/p>\n\n\n\n<p>To enhance this, Python provides a decorator called <code>lru_cache<\/code> from the <code>functools<\/code> module.<\/p>\n\n\n\n<p>The <code>lru_cache<\/code> allows you to cache the result of a function. When you pass the same argument to the function, the function just gets the result from the cache instead of recalculating it.<\/p>\n\n\n\n<p>The following shows how to use the <code>lru_cache<\/code> decorator to speed up the <code>fib<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> functools <span class=\"hljs-keyword\">import<\/span> lru_cache\n\n\n<span class=\"hljs-meta\">@lru_cache<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Calculate the Fibonacci of <span class=\"hljs-subst\">{n}<\/span>'<\/span>)\n    <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> fib(n<span class=\"hljs-number\">-2<\/span>) + fib(n<span class=\"hljs-number\">-1<\/span>)\n\n\nfib(<span class=\"hljs-number\">6<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZnJvbSBmdW5jdG9vbHMgaW1wb3J0IGxydV9jYWNoZQoKCkBscnVfY2FjaGUKZGVmIGZpYihuKToKICAgIHByaW50KGYnQ2FsY3VsYXRlIHRoZSBGaWJvbmFjY2kgb2Yge259JykKICAgIGlmIG4gPCAyOgogICAgICAgIHJldHVybiAxCiAgICByZXR1cm4gZmliKG4tMikgKyBmaWIobi0xKQoKCmZpYig2KQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Calculate the Fibonacci of 6\nCalculate the Fibonacci of 4\nCalculate the Fibonacci of 2\nCalculate the Fibonacci of 0\nCalculate the Fibonacci of 1\nCalculate the Fibonacci of 3\nCalculate the Fibonacci of 5    <\/code><\/span><\/pre>\n\n\n<p>The output shows that the number of calculations is reduced significantly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-fibonacci-sequence-example'>Python Fibonacci sequence example <a href=\"#python-fibonacci-sequence-example\" class=\"anchor\" id=\"python-fibonacci-sequence-example\" title=\"Anchor for Python Fibonacci sequence example\">#<\/a><\/h2>\n\n\n\n<p>First, define a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">class<\/a> that implements the Fibonacci sequence:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Fibonacci<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, n)<\/span>:<\/span>\n        self.n = n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>__init__<\/code> method accepts an integer <code>n<\/code> that specifies the length of the sequence.<\/p>\n\n\n\n<p>Second, define a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-static-methods\/\">static method<\/a> that calculates a Fibonacci number of an integer:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">@staticmethod<\/span>\n<span class=\"hljs-meta\">@lru_cache(2**16)<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(n<span class=\"hljs-number\">-2<\/span>) + Fibonacci.fib(n<span class=\"hljs-number\">-1<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, implement the <code>__len__<\/code> method so that you can use the built-in <code>len<\/code> function to get the number of elements from the Fibonacci sequence:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__len__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> self.n <\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, implement the <code>__getitem__<\/code> method to support indexing through the square brackets syntax:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__getitem__<\/span><span class=\"hljs-params\">(self, index)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">if<\/span> isinstance(index, int):\n        <span class=\"hljs-keyword\">if<\/span> index &lt; <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">or<\/span> index &gt; self.n - <span class=\"hljs-number\">1<\/span>:\n            <span class=\"hljs-keyword\">raise<\/span> IndexError\n\n        <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(index)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>__getitem__<\/code> method accepts an <code>index<\/code> which is an integer. The <code>__getitem__<\/code> checks if the <code>index<\/code> is integer by using the <code>isinstance<\/code> function.<\/p>\n\n\n\n<p>The <code>__getitem__<\/code> method raises the <code>IndexError<\/code> exception if the <code>index<\/code> is out of bounds. Otherwise, it returns the Fibonacci number of the <code>index<\/code>.<\/p>\n\n\n\n<p>Putting it all together.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> functools <span class=\"hljs-keyword\">import<\/span> lru_cache\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Fibonacci<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, n)<\/span>:<\/span>\n        self.n = n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__len__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self.n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__getitem__<\/span><span class=\"hljs-params\">(self, index)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> isinstance(index, int):\n            <span class=\"hljs-keyword\">if<\/span> index &lt; <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">or<\/span> index &gt; self.n - <span class=\"hljs-number\">1<\/span>:\n                <span class=\"hljs-keyword\">raise<\/span> IndexError\n\n            <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(index)\n\n<span class=\"hljs-meta\">    @staticmethod<\/span>\n<span class=\"hljs-meta\">    @lru_cache(2**16)<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(n<span class=\"hljs-number\">-2<\/span>) + Fibonacci.fib(n<span class=\"hljs-number\">-1<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>No, you can save the Fibonacci class in the <code>fibonacci.py<\/code> module and use it in a new script.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='using-fibonacci-sequence'>Using Fibonacci sequence <a href=\"#using-fibonacci-sequence\" class=\"anchor\" id=\"using-fibonacci-sequence\" title=\"Anchor for Using Fibonacci sequence\">#<\/a><\/h2>\n\n\n\n<p>The following shows how to use the Fibonacci sequence from the <code>fibonacci<\/code> module:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fibonacci <span class=\"hljs-keyword\">import<\/span> Fibonacci\n\nfibonacci = Fibonacci(<span class=\"hljs-number\">10<\/span>)\n\n<span class=\"hljs-comment\"># access elements via indices<\/span>\nprint(<span class=\"hljs-string\">'Accessing Fibonacci sequence using &#91;]:'<\/span>)\nprint(fibonacci&#91;<span class=\"hljs-number\">0<\/span>])\nprint(fibonacci&#91;<span class=\"hljs-number\">1<\/span>])\nprint(fibonacci&#91;<span class=\"hljs-number\">2<\/span>])\n\nprint(<span class=\"hljs-string\">'Accessing Fibonacci sequence using for loop:'<\/span>)\n<span class=\"hljs-comment\"># using for loop<\/span>\n<span class=\"hljs-keyword\">for<\/span> f <span class=\"hljs-keyword\">in<\/span> fibonacci:\n    print(f)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-tag\">Accessing<\/span> <span class=\"hljs-selector-tag\">Fibonacci<\/span> <span class=\"hljs-selector-tag\">sequence<\/span> <span class=\"hljs-selector-tag\">using<\/span> <span class=\"hljs-selector-attr\">&#91;]<\/span>:\n1\n1\n2\n<span class=\"hljs-selector-tag\">Accessing<\/span> <span class=\"hljs-selector-tag\">Fibonacci<\/span> <span class=\"hljs-selector-tag\">sequence<\/span> <span class=\"hljs-selector-tag\">using<\/span> <span class=\"hljs-selector-tag\">for<\/span> <span class=\"hljs-selector-tag\">loop<\/span>:\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, create a new instance of the <code>Fibonacci<\/code> sequence that contains 10 elements.<\/li>\n\n\n\n<li>Second, access the Fibonacci sequence&#8217;s elements using the square brackets <code>[]<\/code>.<\/li>\n\n\n\n<li>Third, use the Fibonacci sequence in a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-for-range\/\">for loop<\/a>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='adding-slicing-support'>Adding slicing support <a href=\"#adding-slicing-support\" class=\"anchor\" id=\"adding-slicing-support\" title=\"Anchor for Adding slicing support\">#<\/a><\/h2>\n\n\n\n<p>To support <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-slicing\/\">slicing<\/a> like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-tag\">fibonacci<\/span><span class=\"hljs-selector-attr\">&#91;1:5]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>&#8230;you need to add a logic to handle the <code>slice<\/code> object.<\/p>\n\n\n\n<p>In the <code>fibonacci[1:5]<\/code>, the <code>index<\/code> argument of the <code>__getitem__<\/code> method is a <code>slice<\/code> object whose <code>start<\/code> is 1 and <code>stop<\/code> is 5.<\/p>\n\n\n\n<p>And you can use the <code>indices<\/code> method of the <code>slice<\/code> object to get the indices of elements to return from the sequence:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">indices = index.indices(self.n)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>self.n<\/code> is the length of the sequence that will be sliced. In this case, it&#8217;s the number of elements in the Fibonacci sequence.<\/p>\n\n\n\n<p>To returns a list of Fibonacci from the slice, you can pass the indices to <code>range<\/code> function and use the <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-list-comprehensions\/\">list comprehension<\/a> as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">&#91;Fibonacci.fib(k) <span class=\"hljs-keyword\">for<\/span> k <span class=\"hljs-keyword\">in<\/span> range(*indices)]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following shows the new version of the Fibonacci sequence that supports slicing:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> functools <span class=\"hljs-keyword\">import<\/span> lru_cache\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Fibonacci<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, n)<\/span>:<\/span>\n        self.n = n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__len__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self.n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__getitem__<\/span><span class=\"hljs-params\">(self, index)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> isinstance(index, int):\n            <span class=\"hljs-keyword\">if<\/span> index &lt; <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">or<\/span> index &gt; self.n - <span class=\"hljs-number\">1<\/span>:\n                <span class=\"hljs-keyword\">raise<\/span> IndexError\n\n            <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(index)\n        <span class=\"hljs-keyword\">else<\/span>:\n            indices = index.indices(self.n)\n            <span class=\"hljs-keyword\">return<\/span> &#91;Fibonacci.fib(k) <span class=\"hljs-keyword\">for<\/span> k <span class=\"hljs-keyword\">in<\/span> range(*indices)]\n\n<span class=\"hljs-meta\">    @staticmethod<\/span>\n<span class=\"hljs-meta\">    @lru_cache<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fib<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">if<\/span> n &lt; <span class=\"hljs-number\">2<\/span>:\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">return<\/span> Fibonacci.fib(n<span class=\"hljs-number\">-2<\/span>) + Fibonacci.fib(n<span class=\"hljs-number\">-1<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, you can slice the Fibonacci sequence as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fibonacci <span class=\"hljs-keyword\">import<\/span> Fibonacci\n\nfibonacci = Fibonacci(<span class=\"hljs-number\">10<\/span>)\nprint(fibonacci&#91;<span class=\"hljs-number\">1<\/span>:<span class=\"hljs-number\">5<\/span>])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"JSON \/ JSON with Comments\" data-shcb-language-slug=\"json\"><span><code class=\"hljs language-json\">&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">5<\/span>]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JSON \/ JSON with Comments<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">json<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Implement the <code>__len__<\/code> and <code>__getitem__<\/code> method to define a custom sequence.<\/li>\n\n\n\n<li>The <code>__getitem__<\/code> method need to returns an element based on a given index or raise an IndexError if the index is out of bounds.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1165\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-fibonacci-sequence\/\"\n\t\t\t\tdata-post-title=\"Python Fibonacci Sequence\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1165\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-fibonacci-sequence\/\"\n\t\t\t\tdata-post-title=\"Python Fibonacci Sequence\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to define a custom Sequence type in Python and how to implement the Fibonacci sequence using a custom Sequence type.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":757,"menu_order":17,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1165","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1165","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=1165"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1165\/revisions"}],"predecessor-version":[{"id":7129,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1165\/revisions\/7129"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/757"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=1165"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}