<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python Built-in Functions Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/python-built-in-functions/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/python-built-in-functions/</link>
	<description></description>
	<lastBuildDate>Thu, 25 Apr 2024 14:49:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Python Built-in Functions Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/python-built-in-functions/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python Object Creation: __new__ vs __init__</title>
		<link>https://blog.finxter.com/python-object-creation-__new__-vs-__init__/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 25 Apr 2024 14:49:58 +0000</pubDate>
				<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670130</guid>

					<description><![CDATA[<p>Python&#8217;s magic methods __new__ and __init__ play complementary roles in the lifecycle of an object: 👉 __new__ is a static method, primarily concerned with creating and returning a new instance of a class; it acts before the object is fully instantiated in memory. 👉 Following this, __init__ functions as an instance method, tasked with configuring ... <a title="Python Object Creation: __new__ vs __init__" class="read-more" href="https://blog.finxter.com/python-object-creation-__new__-vs-__init__/" aria-label="Read more about Python Object Creation: __new__ vs __init__">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-object-creation-__new__-vs-__init__/">Python Object Creation: __new__ vs __init__</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-global-color-8-background-color has-background">Python&#8217;s magic methods <code><a href="https://blog.finxter.com/python-__new__-magic-method/" data-type="post" data-id="114351">__new__</a></code> and <code><a href="https://blog.finxter.com/python-init/" data-type="post" data-id="5133">__init__</a></code> play complementary roles in the lifecycle of an object:<br><br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <code>__new__</code> is a static method, primarily concerned with creating and returning a new instance of a class; it acts before the object is fully instantiated in memory. <br><br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Following this, <code>__init__</code> functions as an instance method, tasked with configuring the specific attributes of the newly minted object, thus defining its initial state. </p>



<p>This orchestrated sequence ensures that the structural foundation established by <code>__new__</code> precedes the customization of the object&#8217;s properties through <code>__init__</code>. </p>



<p>This design provides a clear and methodical approach to object creation and initialization in Python.</p>



<h2 class="wp-block-heading">Minimal Example</h2>



<p>Here&#8217;s a simple example that demonstrates the difference between <code>__new__</code> and <code>__init__</code> in Python:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class MyClass:
    def __new__(cls):
        print("Creating instance")
        return super(MyClass, cls).__new__(cls)

    def __init__(self):
        print("Initializing instance")

# Creating an object of MyClass
obj = MyClass()</pre>



<p>In this example:</p>



<ul class="wp-block-list">
<li>When <code>MyClass()</code> is invoked, <code>__new__</code> is called first. It is responsible for creating and returning a new instance of the class. Here, it prints &#8220;Creating instance&#8221; and uses <code>super()</code> to call the <code>__new__</code> method of the superclass to allocate the memory for the new object.</li>



<li>Once the new instance is created and returned by <code>__new__</code>, <code>__init__</code> is called to initialize the new object. In this case, it prints &#8220;Initializing instance&#8221;.</li>
</ul>



<p>This output illustrates the order and roles of <code>__new__</code> and <code>__init__</code> in Python&#8217;s object creation process.</p>



<h2 class="wp-block-heading">FAQ: Understanding <code>__new__</code> and <code>__init__</code> in Python</h2>



<h3 class="wp-block-heading"><strong>1. What is the purpose of <code>__new__</code> in Python?</strong></h3>



<p><code>__new__</code> is a static method responsible for creating a new instance of a class. It is the first step in the instance creation process, handling memory allocation before any attributes are initialized.</p>



<h3 class="wp-block-heading"><strong>2. How does <code>__init__</code> differ from <code>__new__</code>?</strong></h3>



<p>While <code>__new__</code> creates the instance, <code>__init__</code> is tasked with initializing the newly created object&#8217;s attributes. It sets up the initial state of the object after <code>__new__</code> has already created it.</p>



<h3 class="wp-block-heading"><strong>3. When would you need to override <code>__new__</code> instead of <code>__init__</code>?</strong></h3>



<p>Overriding <code>__new__</code> is less common but is necessary when you need to control the creation of a new instance, such as enforcing certain patterns (like singletons), modifying immutable types, or extending immutable types like tuples and strings.</p>



<h3 class="wp-block-heading"><strong>4. Can <code>__init__</code> return a value?</strong></h3>



<p>No, <code>__init__</code> should not return anything except <code>None</code>. It is designed purely for initialization and not for creating new instances, which is the role of <code>__new__</code>.</p>



<h3 class="wp-block-heading"><strong>5. What happens if <code>__new__</code> does not return an instance of the class?</strong></h3>



<p>If <code>__new__</code> returns something that isn&#8217;t an instance of the class in which it&#8217;s defined, then <code>__init__</code> will not be called. This can be used intentionally to control the type of objects your class creates or returns.</p>



<h3 class="wp-block-heading"><strong>6. Is it mandatory to call the base class’s <code>__new__</code> when overriding it?</strong></h3>



<p>Yes, generally you should call the base class’s <code>__new__</code> using <code>super()</code> to ensure that the object gets properly created before you attempt to initialize it in <code>__init__</code>.</p>



<h3 class="wp-block-heading"><strong>7. Can <code>__init__</code> be called multiple times on the same instance?</strong></h3>



<p>Yes, <code>__init__</code> can technically be called multiple times for the same instance, allowing reinitialization of the object. However, <code>__new__</code> is typically called only once per object creation.</p>



<h3 class="wp-block-heading"><strong>8. Are <code>__new__</code> and <code>__init__</code> only relevant to classes defined in Python code?</strong></h3>



<p><code>__new__</code> and <code>__init__</code> are relevant for any class, including those from Python’s standard library or third-party libraries that follow the object-oriented paradigm.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/understanding-the-differences-between-self-and-__init__-methods-in-python-classes/">Understanding the Differences Between self and init Methods in Python Classes</a></p>
<p>The post <a href="https://blog.finxter.com/python-object-creation-__new__-vs-__init__/">Python Object Creation: __new__ vs __init__</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Check If an Integer is in Range</title>
		<link>https://blog.finxter.com/python-check-if-an-integer-is-in-range/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 24 Apr 2024 11:30:45 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670127</guid>

					<description><![CDATA[<p>Problem Formulation You&#8217;re given a number. How do you check if the number lies between two numbers, i.e., a numeric range? When you check if a number lies between two other numbers it returns a boolean that determines if the number is greater than or equal to the minimum number and also less than or ... <a title="Python Check If an Integer is in Range" class="read-more" href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/" aria-label="Read more about Python Check If an Integer is in Range">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/">Python Check If an Integer is in Range</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"><strong>Problem Formulation</strong></h2>



<p><strong>You&#8217;re given a number. How do you check if the number lies between two numbers, i.e., a numeric <em>range</em>?</strong></p>



<p>When you check if a number lies between two other numbers it returns a boolean that determines if the number is greater than or equal to the minimum number and also less than or equal to the maximum number. </p>



<p>Here&#8217;s an example that demonstrates the problem:</p>



<pre class="wp-block-preformatted"><strong>Example 1:</strong> Is 25 between 15 and 35?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>True</code><br><br><strong>Example 2</strong>: Is 0.5 between 1 and 5?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>False</code><br><br><strong>Example 3</strong>: Is 10 between 10 and 20?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>True</code></pre>



<p>Let&#8217;s dive into the trivial solution next &#8212; can you figure out why this is not optimal? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Method 1: Using Python&#8217;s <a href="https://blog.finxter.com/python-membership-in-operator/" target="_blank" rel="noreferrer noopener"><code>in</code></a> Keyword with the <code>range()</code> Function</h2>



<p class="has-global-color-8-background-color has-background">You can use the <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290">range()</a></code> function to determine the upper and lower limits/numbers by feeding in the start and stop values within it. Now, to check if the number lies between the two numbers you can simply use the <strong><code>in</code></strong> keyword to check it. So, if the number lies in the specified range then the output will be &#8220;<em><code>True</code></em>&#8221; else &#8220;<em><code>False</code></em>&#8220;.</p>



<p>Here&#8217;s a simple example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(25 in range(15, 36))  # True
print(0.5 in range(0, 2))  # False
print(10 in range(10, 20))  # True</pre>



<p>Note that the stop value within the <code>range()</code> function should always be one greater than the given maximum number/upper limit since the range of values taken into account by the <code>range</code> function always lies between start to stop-1. Read more about the <code>range()</code> function here:</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong><a href="https://blog.finxter.com/python-range-function/" target="_blank" rel="noreferrer noopener">Python <code>range()</code> Function — A Helpful Illustrated Guide</a></strong></p>



<p class="has-base-2-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Info:</strong> Python’s “<code>in</code>” operator is a reserved <a href="https://blog.finxter.com/python-cheat-sheet/" target="_blank" rel="noreferrer noopener">keyword </a>to test <a href="https://blog.finxter.com/python-membership-in-operator/" data-type="post" data-id="34005">membership</a> of the left operand in the right operand. The right operand, therefore, needs to be a collection type.<br><br>For example, the expression <code>x in my_list checks</code> if object <code>x</code> exists in the <code>my_list</code> collection, so that at least one element <code>y</code> exists in <code>my_list</code> for that <code>x == y</code> holds. <br><br>You can check membership using the “<code>in</code>” operator in collections such as <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">lists</a>, <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">sets</a>, <a href="https://blog.finxter.com/python-string-methods/" target="_blank" rel="noreferrer noopener">strings</a>, and <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener">tuples</a>.</p>



<figure class="wp-block-image size-full is-style-default"><a href="https://blog.finxter.com/python-membership-in-operator/"><img fetchpriority="high" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-71.png" alt="" class="wp-image-699814" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-71.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/09/image-71-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2022/09/image-71-768x432.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>This is not the optimal method because you need to create a whole range of values. Its runtime complexity depends on the size of the range which is really bad when compared to the better alternative: </p>



<h2 class="wp-block-heading">Method 2: Use Comparison Operators</h2>



<p>Python <a href="https://blog.finxter.com/python-comparison-operators/" data-type="post" data-id="33245">comparison operators</a> can compare numerical values such as integers and floats in Python. The operators are: </p>



<ul class="wp-block-list">
<li>equal to ( == ), </li>



<li>not equal to ( != ), </li>



<li>greater than ( > ), </li>



<li>less than ( &lt; ), </li>



<li>less than or equal to ( &lt;= ), and </li>



<li>greater than or equal to ( >= ).</li>
</ul>



<p class="has-global-color-8-background-color has-background">You can use the &lt;= and the >= operators to check if a number lies between the upper limit (maximum number) and lower limit(minimum number).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(15 &lt;= 25 &lt; 35)  # True
print(1 &lt;= 0.5 &lt; 5)  # False
print(10 &lt;= 10 &lt; 20)  # True</pre>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/check-if-a-number-is-between-two-numbers-in-python/">Check If a Number is Between Two Numbers in Python</a></p>



<h2 class="wp-block-heading">Method 3: Using &#8220;and&#8221; Keyword with Comparison Operators</h2>



<p>An alternative way of checking whether a value lies in a range of values is quite similar to the one used above. The only difference, in this case, is to use the <code>and</code> keyword in between the two comparison operators as shown in the solution below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(15 &lt;= 25 and 25 &lt;= 35)  # True
print(1 &lt;= 0.5 and 0.5 &lt;= 5)  # False
print(10 &lt;= 10 and 10 &lt;= 20)  # True</pre>



<p>Some of you might be thinking why use an extra keyword when the solution given before is more readable than this one! Well! That&#8217;s true. The first syntax is more readable but this solution runs faster. Let&#8217;s compare the two solutions using <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_4_Using_timeit_Module" target="_blank">timeit</a></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">~$ python3 -m timeit "10 &lt;= 20 and 20 &lt;= 30"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "10 &lt;= 20 &lt;= 30"
10000000 loops, best of 3: 0.0396 usec per loop</pre>



<h2 class="wp-block-heading">Quick Overview</h2>



<p>Here are various ways to check if a Python integer, <code>x</code>, falls within a specific range:</p>



<ul class="wp-block-list">
<li><strong>Direct Comparison</strong>: <code>if low &lt;= x &lt;= high</code> for inclusive or <code>if low &lt; x &lt; high</code> for exclusive.</li>



<li><strong>Using <code>range()</code></strong>: <code>if x in range(low, high+1)</code> for inclusive or <code>if x in range(low, high)</code> for exclusive.</li>



<li><strong>Boolean Operators</strong>: <code>if x >= low and x &lt;= high</code> for inclusive or <code>if x > low and x &lt; high</code> for exclusive.</li>



<li><strong>Custom Function</strong>: Define a function like <code>def in_range(x, low, high): return low &lt;= x &lt;= high</code> for easy reuse.</li>



<li><strong>Using <code>math</code> module</strong>: <code>import math; if math.isclose(x, low, abs_tol=1e-9) or low &lt; x &lt; high</code> for near lower bound inclusivity.</li>



<li><strong>List Comprehension</strong>: <code>if x in [i for i in range(low, high+1)]</code> offers explicit control over range elements.</li>
</ul>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/list-comprehension/">List Comprehension in Python — A Helpful Illustrated Guide</a></p>
<p>The post <a href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/">Python Check If an Integer is in Range</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Create List From 10 Down to 1</title>
		<link>https://blog.finxter.com/how-to-create-a-python-list-from-10-down-to-1/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 20 Apr 2024 08:24:47 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670101</guid>

					<description><![CDATA[<p>Creating a Python list that counts down from 10 to 1 can be done in several efficient and interesting ways. Below, I explore ten different methods to achieve this, each with an explanation and a code snippet. Method 1: Using range() The range() function is versatile and commonly used for generating sequences of numbers. It ... <a title="Python Create List From 10 Down to 1" class="read-more" href="https://blog.finxter.com/how-to-create-a-python-list-from-10-down-to-1/" aria-label="Read more about Python Create List From 10 Down to 1">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-a-python-list-from-10-down-to-1/">Python Create List From 10 Down to 1</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Creating a Python list that counts down from 10 to 1 can be done in several efficient and interesting ways. Below, I explore ten different methods to achieve this, each with an explanation and a code snippet.</p>



<h2 class="wp-block-heading">Method 1: Using <code>range()</code></h2>



<p>The <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290">range()</a></code> function is versatile and commonly used for generating sequences of numbers. It allows you to specify a start, stop, and step.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = list(range(10, 0, -1))</pre>



<p>This code uses <code>range()</code> to create a sequence starting from 10 and ending just before 1, decrementing by 1 each step. We convert the range to a list.</p>



<h2 class="wp-block-heading">Method 2: List Comprehension</h2>



<p><a href="https://blog.finxter.com/5-best-ways-to-use-list-comprehension-with-dictionaries-in-python/" data-type="post" data-id="1656775">List comprehensions</a> provide a concise way to create lists based on existing lists or iterables.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [x for x in range(10, 0, -1)]</pre>



<p>This snippet creates the same countdown list using a list comprehension, which is a compact way to process and construct lists.</p>



<h2 class="wp-block-heading">Method 3: Using <code>reversed()</code></h2>



<p>The <code><a href="https://blog.finxter.com/python-reversed/" data-type="post" data-id="23565">reversed()</a></code> function can be used to reverse an iterable.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = list(reversed(range(1, 11)))</pre>



<p>Here, <code>reversed()</code> is applied to a range that counts up from 1 to 10, and then we convert the result into a list to get the countdown.</p>



<h2 class="wp-block-heading">Method 4: Using a For Loop</h2>



<p>You can also manually <a href="https://blog.finxter.com/5-best-ways-to-append-an-element-to-a-list-in-python/" data-type="post" data-id="1665198">append items to a list</a> in descending order using a for loop.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = []
for i in range(10, 0, -1):
    numbers.append(i)</pre>



<p>This code manually constructs the list by appending each number from 10 down to 1 in a loop.</p>



<h2 class="wp-block-heading">Method 5: Using a While Loop</h2>



<p>Similarly to a for loop, a while loop can be used to construct the list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = []
i = 10
while i > 0:
    numbers.append(i)
    i -= 1</pre>



<p>This snippet uses a while loop to decrement from 10, appending each number to the list until it reaches 1.</p>



<h2 class="wp-block-heading">Method 6: Using <code>numpy.arange()</code></h2>



<p>If you are using the NumPy library, <code>arange()</code> is a handy function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
numbers = list(np.arange(10, 0, -1))</pre>



<p>NumPy&#8217;s <code><a href="https://blog.finxter.com/numpy-arange/" data-type="post" data-id="548">arange()</a></code> function is used for creating numeric ranges, here generating numbers from 10 to 1, which are then converted to a list.</p>



<h2 class="wp-block-heading">Method 7: Using Recursion</h2>



<p>Recursion can also be used to create a list by counting down.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def countdown(n):
    if n == 0:
        return []
    else:
        return [n] + countdown(n-1)

numbers = countdown(10)</pre>



<p>This recursive function calls itself, decrementing the number each time until it hits zero, creating a list.</p>



<h2 class="wp-block-heading">Method 8: Using <code>itertools.islice()</code></h2>



<p>The <code>itertools</code> module offers an <code>islice()</code> function which can be used to slice iterators.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import itertools
numbers = list(itertools.islice(range(10, 0, -1), 10))</pre>



<p><code>islice()</code> is applied to a range counting down from 10, slicing out the first ten elements.</p>



<h2 class="wp-block-heading">Method 9: Using List Slicing</h2>



<p>You can<a href="https://blog.finxter.com/5-best-ways-to-create-a-list-with-n-elements-from-1-to-n-in-python/" data-type="post" data-id="1662166"> create a list</a> in ascending order and then slice it in reverse.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = list(range(1, 11))[::-1]</pre>



<p>This code creates a list from 1 to 10 and then uses slicing to reverse the order.</p>



<h2 class="wp-block-heading">Method 10: Using <code>sorted()</code></h2>



<p>The <code><a href="https://blog.finxter.com/python-sorted-function/" data-type="post" data-id="18072">sorted()</a></code> function can sort iterables, and it accepts a reverse parameter.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = sorted(range(1, 11), reverse=True)</pre>



<p>This snippet sorts a range from 1 to 10 in reverse order.</p>



<h2 class="wp-block-heading">Summary of Methods</h2>



<ul class="wp-block-list">
<li><strong>Using <code>range()</code>:</strong> Straightforward and common for generating sequences.</li>



<li><strong>List Comprehension:</strong> Concise syntax for creating lists.</li>



<li><strong>Using <code>reversed()</code>:</strong> Handy for reversing any iterable.</li>



<li><strong>Using a For Loop:</strong> Direct and clear method for specific list constructions.</li>



<li><strong>Using a While Loop:</strong> Effective for conditions-based list building.</li>



<li><strong>Using <code>numpy.arange()</code>:</strong> Useful with NumPy for numerical ranges.</li>



<li><strong>Using Recursion:</strong> Elegant but can be less efficient for large numbers.</li>



<li><strong>Using <code>itertools.islice()</code>:</strong> Good for slicing fixed portions of iterators.</li>



<li><strong>Using List Slicing:</strong> Simple to reverse an already created list.</li>



<li><strong>Using <code>sorted()</code>:</strong> Versatile for ordering elements, including in reverse.</li>
</ul>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/python-create-list-from-1-to-n/">How to Create a List From 1 to N</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-a-python-list-from-10-down-to-1/">Python Create List From 10 Down to 1</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Delete File (Ultimate Guide)</title>
		<link>https://blog.finxter.com/python-delete-file-ultimate-guide-2/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sun, 14 Apr 2024 09:53:21 +0000</pubDate>
				<category><![CDATA[File Handling]]></category>
		<category><![CDATA[Input/Output]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670063</guid>

					<description><![CDATA[<p>Python offers several powerful options to handle file operations, including deleting files. Whether you need to check if a file exists before deleting, use patterns to delete multiple files, or automatically delete files under certain conditions, Python has a tool for you. Let&#8217;s delve into various ways you can delete files using Python, ranging from ... <a title="Python Delete File (Ultimate Guide)" class="read-more" href="https://blog.finxter.com/python-delete-file-ultimate-guide-2/" aria-label="Read more about Python Delete File (Ultimate Guide)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-delete-file-ultimate-guide-2/">Python Delete File (Ultimate Guide)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python offers several powerful options to handle file operations, including deleting files. Whether you need to check if a file exists before deleting, use patterns to delete multiple files, or automatically delete files under certain conditions, Python has a tool for you.</p>



<p>Let&#8217;s delve into various ways you can delete files using Python, ranging from straightforward to more complex scenarios.</p>



<h2 class="wp-block-heading">Python Delete File if Exists</h2>



<p>In Python, it&#8217;s good practice to check if a file exists before attempting to delete it to avoid errors. You can achieve this using the <code>os</code> module.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

file_path = 'example.txt'
if os.path.exists(file_path):
    os.remove(file_path)
    print(f"File {file_path} has been deleted.")
else:
    print(f"File {file_path} does not exist.")</pre>



<p>In this code, we first import the <code>os</code> module. We then specify the file path and check if the file exists. If it does, we use <code>os.remove()</code> to delete it and confirm the deletion. If not, we output a message stating the file does not exist.</p>



<h2 class="wp-block-heading">Python Delete File Pathlib</h2>



<p><code>Pathlib</code> is a modern file handling library in Python. It provides an object-oriented approach to manage file systems and works very intuitively.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from pathlib import Path

file_path = Path('example.txt')
if file_path.exists():
    file_path.unlink()
    print(f"File {file_path} has been deleted.")
else:
    print(f"File {file_path} does not exist.")</pre>



<p>Here, we use <code>Path</code> from the <code>pathlib</code> module to create a <code>Path</code> object. We check if the file exists with <code>.exists()</code>, and then use <code>.unlink()</code> to delete it, providing an elegant, readable approach to file deletion.</p>



<h2 class="wp-block-heading">Python Delete File Contents</h2>



<p>If your goal is to clear the contents of a file without deleting the file itself, you can simply open the file in write mode.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">file_path = 'example.txt'
with open(file_path, 'w'):
    print(f"Contents of {file_path} have been cleared.")</pre>



<p>Opening the file in &#8216;write&#8217; mode (<code>'w'</code>) without writing anything effectively erases the file&#8217;s contents, giving you a blank file.</p>



<h2 class="wp-block-heading">Python Delete File OS</h2>



<p>Using the <code>os</code> module is one of the most common ways to delete a file in Python. It&#8217;s straightforward and explicit.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

file_path = 'example.txt'
try:
    os.remove(file_path)
    print(f"File {file_path} successfully deleted.")
except FileNotFoundError:
    print(f"The file {file_path} does not exist.")</pre>



<p>This approach attempts to delete the file and handles the potential <code>FileNotFoundError</code> to avoid crashes if the file doesn&#8217;t exist.</p>



<h2 class="wp-block-heading">Python Delete File with Wildcard</h2>



<p>To delete multiple files that match a pattern, we can combine <code>glob</code> from the <code>glob</code> module with <code>os.remove</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import glob

for file_path in glob.glob('*.txt'):
    os.remove(file_path)
    print(f"Deleted {file_path}")

print("All .txt files deleted.")</pre>



<p>This code snippet finds all <code>.txt</code> files in the current directory and deletes each, providing an efficient way to handle multiple files.</p>



<h2 class="wp-block-heading">Python Delete File After Reading</h2>



<p>If you need to delete a file right after processing its contents, this can be managed smoothly using Python.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">file_path = 'example.txt'
with open(file_path, 'r') as file:
    data = file.read()
    print(f"Read data: {data}")

os.remove(file_path)
print(f"File {file_path} deleted after reading.")</pre>



<p>We read the file, process the contents, and immediately delete the file afterwards. This is particularly useful for temporary files.</p>



<h2 class="wp-block-heading">Python Delete File From Directory if Exists</h2>



<p>Sometimes, we need to target a file inside a specific directory. Checking if the file exists within the directory before deletion can prevent errors.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

directory = 'my_directory'
file_name = 'example.txt'
file_path = os.path.join(directory, file_name)

if os.path.exists(file_path):
    os.remove(file_path)
    print(f"File {file_path} from directory {directory} has been deleted.")
else:
    print(f"File {file_path} does not exist in {directory}.")</pre>



<p>This code constructs the file path, checks its existence, and deletes it if present, all while handling directories.</p>



<h2 class="wp-block-heading">Python Delete File Extension</h2>



<p>Deleting files by extension in a directory is straightforward with Python. Here&#8217;s how you might delete all <code>.log</code> files in a directory:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

directory = '/path_to_directory'
for file_name in os.listdir(directory):
    if file_name.endswith('.log'):
        os.remove(os.path.join(directory, file_name))
        print(f"Deleted {file_name}")</pre>



<p>This loops through all files in the given directory, checks if they end with <code>.log</code>, and deletes them.</p>



<h2 class="wp-block-heading">Python Delete File on Exit</h2>



<p>To ensure files are deleted when a Python script is done executing, use <code>atexit</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import atexit
import os

file_path = 'temporary_file.txt'
open(file_path, 'a').close()  # Create the file

def cleanup():
    os.remove(file_path)
    print(f"File {file_path} has been deleted on exit.")

atexit.register(cleanup)</pre>



<p>This code sets up a cleanup function that deletes a specified file and registers this function to be called when the script exits.</p>



<h2 class="wp-block-heading">Python Delete File After Time</h2>



<p>For deleting files after a certain period, use <code>time</code> and <code>os</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import time

file_path = 'old_file.txt'
time_to_wait = 10  # seconds

time.sleep(time_to_wait)
os.remove(file_path)
print(f"File {file_path} deleted after {time_to_wait} seconds.")</pre>



<p>After waiting for a specified time, the file is deleted, which can be useful for timed file cleanup tasks.</p>



<h3 class="wp-block-heading">Summary</h3>



<ul class="wp-block-list">
<li><strong>Delete if Exists</strong>: Use <code>os.path.exists()</code> and <code>os.remove()</code>.</li>



<li><strong>Pathlib</strong>: Employ <code>Path.exists()</code> and <code>Path.unlink()</code>.</li>



<li><strong>Delete Contents</strong>: Open in &#8216;write&#8217; mode.</li>



<li><strong>OS Module</strong>: Directly use <code>os.remove()</code>.</li>



<li><strong>Wildcard Deletion</strong>: Utilize <code>glob.glob()</code> and <code>os.remove()</code>.</li>



<li><strong>After Reading</strong>: Delete following file read operations.</li>



<li><strong>From Directory if Exists</strong>: Construct path with <code>os.path.join()</code>.</li>



<li><strong>Delete File Extension</strong>: Loop through directory and delete based on extension.</li>



<li><strong>On Exit</strong>: Use <code>atexit.register()</code>.</li>



<li><strong>After Time</strong>: Combine <code>time.sleep()</code> with <code>os.remove()</code>.</li>
</ul>



<p>Each method provides a robust way to handle different file deletion scenarios efficiently and securely in Python. Choose the one that best suits your needs to maintain sleek and effective code.</p>
<p>The post <a href="https://blog.finxter.com/python-delete-file-ultimate-guide-2/">Python Delete File (Ultimate Guide)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python: Create List from 1 to N</title>
		<link>https://blog.finxter.com/python-create-list-from-1-to-n-2/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 10 Apr 2024 13:58:16 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670018</guid>

					<description><![CDATA[<p>Creating a list containing a range of numbers from 1 to N in Python can be achieved through several methods. Here’s a concise list of alternative solutions: Method 1. List Comprehension with range() This method utilizes list comprehension, a concise way to create lists. The range(1, N+1) generates numbers from 1 to N, and the ... <a title="Python: Create List from 1 to N" class="read-more" href="https://blog.finxter.com/python-create-list-from-1-to-n-2/" aria-label="Read more about Python: Create List from 1 to N">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-create-list-from-1-to-n-2/">Python: Create List from 1 to N</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Creating a list containing a range of numbers from 1 to <code>N</code> in Python can be achieved through several methods. Here’s a concise list of alternative solutions:</p>



<ul class="has-global-color-8-background-color has-background wp-block-list">
<li><strong>Method 1: </strong>Using the <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290">range()</a></code> function with a list comprehension.</li>



<li><strong>Method 2: </strong>Utilizing the <code>range()</code> function with the <code><a href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502">list()</a></code> constructor.</li>



<li><strong>Method 3: </strong>Employing a loop to manually append numbers.</li>
</ul>



<h2 class="wp-block-heading">Method 1. List Comprehension with <code>range()</code></h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">N = 10
list_from_1_to_N = [i for i in range(1, N+1)]</pre>



<p>This method utilizes list comprehension, a concise way to create lists. The <code>range(1, N+1)</code> generates numbers from 1 to <code>N</code>, and the list comprehension constructs a list from these numbers.</p>



<h2 class="wp-block-heading">Method 2. <code>list()</code> Constructor with <code>range()</code></h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">N = 10
list_from_1_to_N = list(range(1, N+1))</pre>



<p>The <code>list()</code> constructor is used to convert the range of numbers generated by <code>range(1, N+1)</code> into a list. It&#8217;s a straightforward approach, suitable for beginners.</p>



<h2 class="wp-block-heading">Method 3. Looping and Appending</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">N = 10
list_from_1_to_N = []
for i in range(1, N+1):
    list_from_1_to_N.append(i)</pre>



<p>In this method, a for loop iterates through each number generated by <code>range(1, N+1)</code>, and each number is appended to the list manually. This approach is more verbose but illustrates the process of building a list step by step.</p>



<p>You can find more ways in this more comprehensive article:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2024/04/image-174-1024x572.png" alt="" class="wp-image-1670019" srcset="https://blog.finxter.com/wp-content/uploads/2024/04/image-174-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/04/image-174-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2024/04/image-174-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2024/04/image-174.png 1273w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/python-create-list-from-1-to-n/">Python Create List from 1 to N</a></p>
<p>The post <a href="https://blog.finxter.com/python-create-list-from-1-to-n-2/">Python: Create List from 1 to N</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial</title>
		<link>https://blog.finxter.com/can-i-write-a-for-loop-and-if-statement-in-a-single-line-a-simple-python-tutorial/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 09 Apr 2024 13:52:07 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Python One-Liners]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670012</guid>

					<description><![CDATA[<p>Python&#8217;s elegance and readability often come from its ability to execute powerful operations in a single line of code. One such instance is the combination of for loops and if statements into a list comprehension. Understanding the Basics At its core, a list comprehension offers a succinct way to create lists. The syntax [expression for ... <a title="Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial" class="read-more" href="https://blog.finxter.com/can-i-write-a-for-loop-and-if-statement-in-a-single-line-a-simple-python-tutorial/" aria-label="Read more about Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/can-i-write-a-for-loop-and-if-statement-in-a-single-line-a-simple-python-tutorial/">Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python&#8217;s elegance and readability often come from its ability to execute powerful operations in a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" data-type="post" data-id="5394">single line of code</a>.<strong> One such instance is the combination of <code>for</code> loops and <code>if</code> statements into a list comprehension.</strong> </p>



<h2 class="wp-block-heading">Understanding the Basics</h2>



<p class="has-global-color-8-background-color has-background">At its core, a <a href="https://blog.finxter.com/5-best-ways-to-use-list-comprehension-with-dictionaries-in-python/" data-type="post" data-id="1656775">list comprehension</a> offers a succinct way to create lists. The syntax <code>[expression for item in iterable if condition]</code> allows for iterating over <code><a href="https://blog.finxter.com/5-best-ways-to-print-python-iterables/" data-type="post" data-id="1657195">iterable</a></code>, applying <code>condition</code> to each <code>item</code>, and then including the transformed <code>expression</code> of <code>item</code> in a new list.</p>



<p>Here&#8217;s an example</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = ["one", "two", "three"]
filtered_list = [i for i in my_list if i == "two"]
print(filtered_list)</pre>



<p>This will output <code>['two']</code>, demonstrating how list comprehensions filter elements.</p>



<h2 class="wp-block-heading">Another Example</h2>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="613" src="https://blog.finxter.com/wp-content/uploads/2024/03/image-50-1024x613.png" alt="" class="wp-image-1669912" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/image-50-1024x613.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/03/image-50-300x179.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/image-50-768x459.png 768w, https://blog.finxter.com/wp-content/uploads/2024/03/image-50.png 1140w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>You can use list comprehensions for filtering elements from a list. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Example</strong>: If you have <code>colors = ["red", "blue", "green"]</code> and you want to filter out only &#8220;blue&#8221;, a list comprehension like <code>[color for color in colors if color == "blue"]</code> would return <code>['blue']</code>. </p>



<p>However, the variable <code>color</code> will hold the value &#8220;green&#8221; after the comprehension runs, being the last item iterated.</p>



<p>To extract a specific item, it&#8217;s suggested to utilize a <code>for</code> loop with a <code>break</code> statement for clarity:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for color in colors:
    if color == 'blue':
        break</pre>



<p>For a concise approach, <code>next()</code> is recommended with a generator expression:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">found_color = next((color for color in colors if color == 'blue'), None)</pre>



<p>This returns &#8220;blue&#8221; or <code>None</code> if not found. Alternatively, for a simple existence check, a direct conditional can be used:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">color_match = 'blue' if 'blue' in colors else None</pre>



<h2 class="wp-block-heading">The Variable Scope Challenge</h2>



<p>A common confusion arises regarding the scope of the loop variable used in a comprehension. For instance, after running a list comprehension, attempting to print the loop variable might not yield the expected result, as it retains its last assigned value from the loop.</p>



<p>To avoid such confusion, especially when looking for a single match, Python&#8217;s <code><a href="https://blog.finxter.com/python-next/" data-type="post" data-id="17135">next()</a></code> function can be employed alongside a <a href="https://blog.finxter.com/python-generator-expressions/" data-type="post" data-id="975287">generator expression</a>. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = ["one", "two", "three"]
matching_element = next((elem for elem in my_list if elem == "two"), None)
print(matching_element)</pre>



<p>This will correctly print <code>'two'</code> or <code>None</code> if no match is found, resolving the variable scope challenge elegantly.</p>



<h2 class="wp-block-heading">Advanced Filtering and Matching</h2>



<p class="has-global-color-8-background-color has-background">Beyond simple matching, Python allows for more sophisticated queries within a list, such as finding elements that match complex conditions or even using an <code>else</code> clause within the comprehension for alternative actions.</p>



<p>An example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3]
filtered = [i if i == 2 else "not two" for i in my_list]
print(filtered)</pre>



<p>This will output <code>['not two', 2, 'not two']</code>, demonstrating conditional logic within a list comprehension.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" data-type="link" data-id="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/">Python One Line For Loop [A Simple Tutorial]</a></p>
<p>The post <a href="https://blog.finxter.com/can-i-write-a-for-loop-and-if-statement-in-a-single-line-a-simple-python-tutorial/">Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Avoid Circular Imports in Python?</title>
		<link>https://blog.finxter.com/how-to-avoid-circular-imports-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 08 Apr 2024 11:34:08 +0000</pubDate>
				<category><![CDATA[Dependency Management]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670007</guid>

					<description><![CDATA[<p>Imagine you and your friend are trying to decide who goes through the door first. You say, &#8220;After you,&#8221; and your friend says, &#8220;No, no, after you.&#8221; And there you both stand&#8230; forever. In Python, this happens when Module A needs something from Module B, but Module B also needs something from Module A. It&#8217;s ... <a title="How to Avoid Circular Imports in Python?" class="read-more" href="https://blog.finxter.com/how-to-avoid-circular-imports-in-python/" aria-label="Read more about How to Avoid Circular Imports in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-avoid-circular-imports-in-python/">How to Avoid Circular Imports in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Imagine you and your friend are trying to decide who goes through the door first. You say, <em>&#8220;After you,&#8221;</em> and your friend says, <em>&#8220;No, no, after you.&#8221;</em> And there you both stand&#8230; forever. </p>



<p>In Python, this happens when Module A needs something from Module B, but Module B also needs something from Module A. It&#8217;s a standoff, and nobody wins.</p>



<h2 class="wp-block-heading">Example of Circular Import</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="934" height="795" src="https://blog.finxter.com/wp-content/uploads/2024/04/image-10.png" alt="" class="wp-image-1670008" srcset="https://blog.finxter.com/wp-content/uploads/2024/04/image-10.png 934w, https://blog.finxter.com/wp-content/uploads/2024/04/image-10-300x255.png 300w, https://blog.finxter.com/wp-content/uploads/2024/04/image-10-768x654.png 768w" sizes="auto, (max-width: 934px) 100vw, 934px" /></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Example</strong>: Imagine you have two Python files: <code>vehicles.py</code> and <code>garage.py</code>. In <code>vehicles.py</code>, you define a class <code>Car</code> that needs to check if a given car is currently stored in a garage from <code>garage.py</code>. <br><br>Conversely, <code>garage.py</code> defines a class <code>Garage</code> that stores cars, and for some functionality, it needs to create car instances using the <code>Car</code> class defined in <code>vehicles.py</code>. If both files attempt to import each other at the top, Python will stumble into a circular import. <br><br>When you try to run one of the modules, Python will try to load <code>vehicles.py</code>, which in turn tries to load <code>garage.py</code> before it has finished loading <code>vehicles.py</code>, leading to errors or unexpected behavior because one module is trying to use parts of the other before they are fully available.</p>



<p>To illustrate the circular import issue with a technical example, let&#8217;s create the code for the <code>vehicles.py</code> and <code>garage.py</code> scenario mentioned earlier.</p>



<h3 class="wp-block-heading"><code>vehicles.py</code></h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from garage import Garage  # This causes a circular import

class Car:
    def __init__(self, model):
        self.model = model

    def is_in_garage(self):
        # Checks if the car is in the garage
        return Garage().contains(self.model)</pre>



<h3 class="wp-block-heading"><code>garage.py</code></h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from vehicles import Car  # This causes a circular import

class Garage:
    def __init__(self):
        self.cars = []

    def add_car(self, model):
        car = Car(model)  # Creating a Car instance
        self.cars.append(car)

    def contains(self, model):
        return any(car.model == model for car in self.cars)</pre>



<p>In this scenario, <code>vehicles.py</code> imports <code>Garage</code> from <code>garage.py</code> at the top level, and <code>garage.py</code> does the same with <code>Car</code> from <code>vehicles.py</code>, creating a circular import problem. When either <code>vehicles.py</code> or <code>garage.py</code> is run, Python encounters an import statement that leads it into a loop, causing errors because it tries to access functionality from a module that has not been fully loaded yet.</p>



<h2 class="wp-block-heading">General Solution Method</h2>



<p>To resolve the circular import issue in our <code>vehicles.py</code> and <code>garage.py</code> example, one effective solution is to move the import statements inside the functions or methods where they are actually needed. This way, the import happens at runtime, when the function is called, rather than at the module&#8217;s load time, thereby avoiding the circular dependency problem. This method is particularly useful when the imported functionality is not required immediately when the module is loaded but rather at a specific point during execution, such as within a method&#8217;s body.</p>



<h3 class="wp-block-heading">Fixed <code>vehicles.py</code></h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Removed the import from the top to inside the method
class Car:
    def __init__(self, model):
        self.model = model

    def is_in_garage(self):
        from garage import Garage  # Import moved inside the method
        return Garage().contains(self.model)</pre>



<h3 class="wp-block-heading">Fixed <code>garage.py</code></h3>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Kept the import of Car inside the method that needs it
class Garage:
    def __init__(self):
        self.cars = []

    def add_car(self, model):
        from vehicles import Car  # Import moved inside the method
        car = Car(model)  # Creating a Car instance
        self.cars.append(car)

    def contains(self, model):
        return any(car.model == model for car in self.cars)</pre>



<p>With this approach, the circular import is resolved because <code>Garage</code> is only imported within <code>Car.is_in_garage()</code> when it&#8217;s needed, and similarly, <code>Car</code> is imported within <code>Garage.add_car()</code> only at the point of use. This ensures that both classes can be defined without requiring each other at the top level, thus avoiding the loop of imports.</p>



<p>Let&#8217;s have a look at multiple (alternative) solution methods next! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">Method 1: Merge Together</h2>



<p class="has-global-color-8-background-color has-background">If Module A and Module B are inseparable, why not combine them into one big Module C? It simplifies things!</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Before: A.py and B.py are two separate files causing issues.
# After: Combine into C.py where everything lives happily ever after.
</pre>



<h2 class="wp-block-heading">Method 2: Take Turns</h2>



<p class="has-global-color-8-background-color has-background">What if you took turns? Move the import inside a function. This way, the code only tries to import when the function is called, potentially avoiding the standoff.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># In A.py
def dance_with_b():
    from B import b_dance
    b_dance()
</pre>



<h2 class="wp-block-heading">Method 3: Change the Routine</h2>



<p class="has-global-color-8-background-color has-background">Sometimes, the dance steps are too complicated. Maybe Module A and Module B don&#8217;t need to be so dependent on each other. Split them up or reorganize the steps so that they flow in one direction.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Instead of A importing B and B importing A,
# Split B into B1 and B2 where B1 can safely import A and B2 does not.
</pre>



<h2 class="wp-block-heading">Method 4: Use a Choreographer <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4dd.png" alt="📝" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p class="has-global-color-8-background-color has-background">Packages in Python can use an <code><a href="https://blog.finxter.com/python-init/" data-type="post" data-id="5133">__init__.py</a></code> file to manage imports like a choreographer managing dancers. It can help organize and control how modules interact with each other.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Inside your package's __init__.py
from .A import A
from .B import B
</pre>



<h2 class="wp-block-heading">Method 5: Dance by Proxy <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3ad.png" alt="🎭" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p class="has-global-color-8-background-color has-background">Inversion of Control (IoC) is like hiring a dance proxy. Instead of Module A and B directly interacting, they pass messages or objects through an intermediary. It&#8217;s a bit like sending love letters instead of talking directly.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># A and B communicate through an intermediary, avoiding direct imports.
</pre>



<h2 class="wp-block-heading">Method 6: Sign Language <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f91f.png" alt="🤟" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p class="has-global-color-8-background-color has-background">Abstract Base Classes (ABCs) work like sign language for modules. They define a common language (interface) that both modules can understand without directly communicating.</p>



<p><strong>Example:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># ABCs.py defines a common interface.
# A.py and B.py both import ABCs.py but not each other.
</pre>
<p>The post <a href="https://blog.finxter.com/how-to-avoid-circular-imports-in-python/">How to Avoid Circular Imports in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</title>
		<link>https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 30 Mar 2024 17:27:56 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Statistics]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669952</guid>

					<description><![CDATA[<p>To generate random samples from a power-law distribution in Python, use the numpy library for numerical operations and matplotlib for visualization. Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution: First, we import the necessary libraries: numpy for generating the power-law distributed samples and matplotlib.pyplot for plotting. The a ... <a title="How to Generate and Plot Random Samples from a Power-Law Distribution in Python?" class="read-more" href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/" aria-label="Read more about How to Generate and Plot Random Samples from a Power-Law Distribution in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>To generate random samples from a <a href="https://blog.finxter.com/5-best-ways-to-create-logarithmic-y-axis-bins-in-python/" data-type="post" data-id="1664973">power-law distribution</a> in Python, use the <code>numpy</code> library for numerical operations and <code>matplotlib</code> for visualization. </p>



<ul class="wp-block-list">
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4f1.png" alt="📱" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Computation</strong>: Specifically, you can use the <code>numpy.random.power</code> function, which draws samples from a power-law distribution with a specific exponent. </li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Visualization</strong>: After generating the samples, it&#8217;s beneficial to visualize them in a log-log space to observe the characteristic straight-line behavior of power-law distributions. This visualization helps in understanding the distribution&#8217;s properties and confirming its power-law nature.</li>
</ul>



<p>Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

# Parameters
a = 5  # Shape parameter
samples = 10000  # Number of samples

# Generate random samples
data = np.random.power(a, samples)

# Visualization in log-log space
counts, bins = np.histogram(data, bins=50)
bins_center = (bins[:-1] + bins[1:]) / 2
plt.loglog(bins_center, counts, marker='o', linestyle='none')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Power-law distribution in log-log space')
plt.show()</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png" alt="" class="wp-image-1669956" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3-300x242.png 300w" sizes="auto, (max-width: 570px) 100vw, 570px" /></figure>
</div>


<p>First, we import the necessary libraries: <code>numpy</code> for generating the power-law distributed samples and <code>matplotlib.pyplot</code> for plotting.</p>



<p>The <code>a</code> parameter is the shape parameter of the power-law distribution, controlling the steepness of the distribution. The <code>samples</code> variable defines how many <a href="https://blog.finxter.com/5-secure-ways-to-generate-random-numbers-in-python/" data-type="post" data-id="1668905">random values we want to generate</a>.</p>



<p><code>np.random.power(a, samples)</code> generates an array of samples drawn from a power-law distribution with the shape parameter <code>a</code>.</p>



<p>To visualize the distribution in log-log space, we first compute the histogram of the data using <code>np.histogram</code>, which returns the counts and the bin edges.</p>



<p>We calculate the center of each bin for plotting purposes (<code>bins_center</code>) and then plot the histogram using <code>plt.loglog</code> to create a log-log plot. This is crucial for visualizing power-law distributions as they appear as straight lines in log-log plots.</p>



<p>Finally, we label the axes and show the plot with <code>plt.show()</code>.</p>



<h2 class="wp-block-heading">Creating Power Law Distribution Without Library Such As NumPy</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png" alt="" class="wp-image-1669957" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4-300x242.png 300w" sizes="auto, (max-width: 570px) 100vw, 570px" /></figure>
</div>


<p class="has-global-color-8-background-color has-background">To create samples from a power-law distribution without a library, we use the inverse transform sampling method, where we <a href="https://blog.finxter.com/5-best-ways-to-generate-pseudo-random-numbers-in-python/" data-type="post" data-id="1669034">generate uniform random samples</a> and apply the inverse of the distribution&#8217;s cumulative distribution function (CDF) to these samples. This approach mathematically transforms uniformly distributed random numbers into numbers that follow the desired power-law distribution, based on the power-law&#8217;s specific characteristics and parameters.</p>



<p>Here&#8217;s the code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random
import matplotlib.pyplot as plt

def generate_power_law_samples(alpha, size=1000, xmin=1):
    """Generate samples from a power-law distribution using the inverse transform sampling method."""
    samples = []
    for _ in range(size):
        u = random.random()  # Uniform random sample from 0 to 1
        x = xmin * (1 - u) ** (-1 / (alpha - 1))
        samples.append(x)
    return samples

def plot_rank_frequency(samples):
    """Plot samples in log-log space using rank-frequency."""
    # Sort samples in descending order
    sorted_samples = sorted(samples, reverse=True)
    # Generate ranks
    ranks = range(1, len(sorted_samples) + 1)
    # Plotting
    plt.loglog(ranks, sorted_samples, marker='o', linestyle='none')
    plt.xlabel('Rank')
    plt.ylabel('Sample Value')
    plt.title('Power-law distribution rank-frequency plot in log-log space')
    plt.show()

# Generate samples
alpha = 2.5  # Shape parameter of the power-law distribution
samples = generate_power_law_samples(alpha, 10000)

# Plot rank-frequency in log-log space
plot_rank_frequency(samples)
</pre>



<p></p>



<p>This code generates samples from a power-law distribution using the <code>generate_power_law_samples</code> function, as before.</p>



<p>The <code>plot_rank_frequency</code> function sorts the samples in descending order and then generates their ranks. In a rank-frequency plot, each point&#8217;s x-coordinate is its rank (i.e., its position in the sorted list), and its y-coordinate is the sample value itself.</p>



<p>We plot these points in a log-log space using <code>plt.loglog()</code>. This type of plot is useful for observing the power-law behavior of the distribution, where a linear relationship in log-log space indicates a power-law distribution.</p>



<p>The plot&#8217;s x-axis represents the ranks of the samples, and the y-axis represents the sample values, both on logarithmic scales. This visualization technique is effective for highlighting the characteristics of power-law distributions.</p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python &#8211; How to Check If Number Is Odd</title>
		<link>https://blog.finxter.com/python-how-to-check-if-number-is-odd/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 13 Feb 2024 12:10:02 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1654906</guid>

					<description><![CDATA[<p>💡 Problem Formulation: This article addresses how one can identify odd numbers using the Python programming language. We define an odd number as an integer which is not divisible by 2 without a remainder. For instance, given the input 7, the desired output is a confirmation that 7 is indeed an odd number. Method 1: ... <a title="Python &#8211; How to Check If Number Is Odd" class="read-more" href="https://blog.finxter.com/python-how-to-check-if-number-is-odd/" aria-label="Read more about Python &#8211; How to Check If Number Is Odd">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-how-to-check-if-number-is-odd/">Python &#8211; How to Check If Number Is Odd</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Problem Formulation</strong>: This article addresses how one can identify odd numbers using the Python programming language. We define an odd number as an integer which is not divisible by 2 without a remainder. For instance, given the input <code>7</code>, the desired output is a confirmation that <code>7</code> is indeed an odd number.</p>



<h2 class="wp-block-heading">Method 1: The Modulo Operator <code>%</code></h2>



<p class="has-global-color-8-background-color has-background">The <a href="https://blog.finxter.com/python-get-quotient-and-remainder-with-divmod/" data-type="post" data-id="1646469">modulo operator (<code>%</code>)</a> in Python returns the remainder of a division. When used, it checks whether a number is evenly divisible by another. To determine if a number is odd, you would check if the modulo with 2 returns a remainder of 1.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">number = 27
is_odd = number % 2 == 1

print(f"Is {number} odd? {is_odd}")</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Is 27 odd? True</pre>



<p>By using the modulo operation <code>number % 2</code>, we effectively ask if there&#8217;s a remainder when <code>number</code> is divided by 2. For all odd numbers, this division will leave a remainder of 1, meaning the expression will evaluate to <code>True</code>.</p>



<h2 class="wp-block-heading">Method 2: Bitwise AND Operator</h2>



<p class="has-global-color-8-background-color has-background">The <a href="https://blog.finxter.com/python-bitwise-and-operator/" data-type="post" data-id="32148">bitwise AND operator (<code>&amp;</code>)</a> can be used to compare the binary representation of numbers. Since all odd numbers have the least significant bit set to 1, performing a bitwise AND with 1 will result in 1 if the number is odd.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">number = 42
is_odd = number &amp; 1

print(f"Is {number} odd? {bool(is_odd)}")</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Is 42 odd? False</pre>



<p>This snippet uses the expression <code>number &amp; 1</code> which focuses on the least significant bit of the number. If that bit is 1 (which is true for odd numbers), the result will be <code>True</code> when converted to a Boolean.</p>



<h2 class="wp-block-heading">Method 3: Subtraction and Comparison</h2>



<p class="has-global-color-8-background-color has-background">Another method to check if a number is odd is to subtract 1 from the number and then perform the modulo operation. If the result is 0, then the original number was odd.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">number = 19
is_odd = (number - 1) % 2 == 0

print(f"Is {number} odd? {is_odd}")</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Is 19 odd? True</pre>



<p>By subtracting 1 from an odd number, you get an even number. Therefore, when taking modulo 2 of this result, you&#8217;ll get 0. This confirms that the original number was odd.</p>



<h2 class="wp-block-heading">Method 4: Using the Division Remainder Directly</h2>



<p class="has-global-color-8-background-color has-background">Python&#8217;s <code><a href="https://blog.finxter.com/python-divmod/" data-type="post" data-id="20328">divmod()</a></code> function returns a tuple containing the quotient and the remainder of dividing the first number by the second. You can use the remainder directly to check for oddness.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2,3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">number = 58
_, remainder = divmod(number, 2)
is_odd = remainder == 1

print(f"Is {number} odd? {is_odd}")</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Is 58 odd? False</pre>



<p>The <code>divmod(number, 2)</code> function returns a pair where the second value is the remainder of the division of <code>number</code> by 2. Comparing this remainder to 1 directly checks if the number is odd.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using the int() Casting</h2>



<p class="has-global-color-8-background-color has-background">Casting the number to an integer after dividing it by 2 and then doubling it should give the original number if it is even. If the number is odd, this operation will result in a number less than the original, confirming its oddness in a Boolean context.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">number = 77
is_odd = number == (int(number / 2) * 2) + 1

print(f"Is {number} odd? {is_odd}")</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Is 77 odd? True</pre>



<p>This one-liner casts the result of <code>number / 2</code> to an integer, effectively truncating the decimal, and then multiplies it by 2 before adding 1. If the resulting value equals the original <code>number</code>, it confirms that the number is odd.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>



<ul class="wp-block-list">
<li><strong>Method 1: The Modulo Operator.</strong> Strengths: Direct and universally understood. Weaknesses: None notable.</li>



<li><strong>Method 2: Bitwise AND Operator.</strong> Strengths: Fast, low-level operation. Weaknesses: Can be unintuitive to those unfamiliar with bitwise operations.</li>



<li><strong>Method 3: Subtraction and Comparison.</strong> Strengths: Conceptually simple alteration of the typical modulo approach. Weaknesses: Slightly more convoluted, less direct.</li>



<li><strong>Method 4: Using the Division Remainder Directly.</strong> Strengths: Utilizes built-in function divmod; very clear. Weaknesses: Slightly slower due to tuple unpacking, overkill for such a simple check.</li>



<li><strong>Bonus One-Liner Method 5: Using the int() Casting.</strong> Strengths: Clever use of casting and arithmetic to determine oddness; one-liner. Weaknesses: May not be as immediately clear in intent, which can affect code readability.</li>
</ul>
<p>The post <a href="https://blog.finxter.com/python-how-to-check-if-number-is-odd/">Python &#8211; How to Check If Number Is Odd</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Check If Number Is Even in Python</title>
		<link>https://blog.finxter.com/5-best-ways-to-check-if-number-is-even-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 13 Feb 2024 12:06:08 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1654904</guid>

					<description><![CDATA[<p>💡 Problem Formulation: Determining the parity of an integer in Python involves checking whether it is divisible by 2 without any remainder. Typically, you might have an integer n and you want to get back a Boolean value, True if n is even, and False if it is not. For example, given n = 4, ... <a title="5 Best Ways to Check If Number Is Even in Python" class="read-more" href="https://blog.finxter.com/5-best-ways-to-check-if-number-is-even-in-python/" aria-label="Read more about 5 Best Ways to Check If Number Is Even in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-check-if-number-is-even-in-python/">5 Best Ways to Check If Number Is Even in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Problem Formulation:</strong> Determining the parity of an integer in Python involves checking whether it is divisible by 2 without any remainder. Typically, you might have an integer <code>n</code> and you want to get back a Boolean value, <code>True</code> if <code>n</code> is even, and <code>False</code> if it is not. For example, given <code>n = 4</code>, you want to end up with <code>True</code>, as <code>4</code> is an even number.</p>



<h2 class="wp-block-heading">Method 1: Using The Modulus Operator</h2>



<p class="has-global-color-8-background-color has-background">The <a href="https://blog.finxter.com/python-get-quotient-and-remainder-with-divmod/" data-type="post" data-id="1646469">modulus operator (<code>%</code>)</a> returns the remainder of a division operation. If a number is divisible by 2 with no remainder, it is even. This method uses the modulus operator to check whether the remainder of the division of a number by 2 is zero.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def is_even(num):
    return num % 2 == 0

print(is_even(10))  # Is 10 an even number?
print(is_even(11))  # How about 11?</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False</pre>



<p>In this code snippet, we define a function <code>is_even</code> that takes a single parameter <code>num</code>. We return <code>True</code> if the remainder of <code>num</code> divided by 2 is 0, which means the number is even. The print statements demonstrate the function in action, returning <code>True</code> for 10 and <code>False</code> for 11.</p>



<h2 class="wp-block-heading">Method 2: Using Bitwise AND Operator</h2>



<p class="has-global-color-8-background-color has-background">The <a href="https://blog.finxter.com/python-bitwise-and-operator/" data-type="post" data-id="32148">bitwise AND operator (<code>&amp;</code>)</a> compares each bit of the number to the corresponding bit of another number. If both bits are 1, it gives 1. Even numbers have their least significant bit as 0. Therefore, performing a bitwise AND operation with 1 can determine if a number is even or odd.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def is_even(num):
    return (num &amp; 1) == 0

print(is_even(42))  # Let's check the answer to life!
print(is_even(77))  # What about a lucky number 77?</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False</pre>



<p>The function <code>is_even</code> here checks if the least significant bit of <code>num</code> is 0. Since even numbers always have 0 as the least significant bit, <code>num &amp; 1</code> will be 0 for them. For the number 42, which is even, it returns <code>True</code> and <code>False</code> for the odd number 77.</p>



<h2 class="wp-block-heading">Method 3: Using Division and Multiplication</h2>



<p class="has-global-color-8-background-color has-background">Another way to check for an even number is to divide the number by 2, multiply the quotient by 2, and then compare it with the original number. If they are the same, the number is even.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def is_even(num):
    return (num // 2) * 2 == num

print(is_even(2022))  # A recent even year.
print(is_even(1989))  # The year Taylor Swift was born.</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False</pre>



<p>In this code, the <code>is_even</code> function checks if the result of integer division of <code>num</code> by 2, when multiplied back by 2, equals <code>num</code>. This works because integer division by 2 drops the decimal place, effectively ignoring the remainder if it was an odd number. For 2022, which is even, it returns true. It returns false for 1989, which is odd.</p>



<h2 class="wp-block-heading">Method 4: Using The Float Division</h2>



<p class="has-global-color-8-background-color has-background"><a href="https://blog.finxter.com/division-in-python/" data-type="post" data-id="16457">Float division</a> can also be used to determine evenness. By dividing the number by 2 and checking if the result is a whole number, one can infer whether the original number is even. For whole numbers, the mantissa of the floating-point result will be <code>.0</code>.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def is_even(num):
    return num / 2.0 % 1 == 0

print(is_even(64))  # Can this power of two confirm?
print(is_even(81))  # Maybe a square of an odd number?</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False</pre>



<p>By dividing the number by 2.0 (to enforce float division), the <code>is_even</code> function then checks if there&#8217;s any remainder when dividing the result by 1. If there’s none (remainder is <code>0</code>), then the number must be even, since it’s fully divisible by 2. This test validates that 64 is even and 81 is not.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using Lambda</h2>



<p class="has-global-color-8-background-color has-background">For those who appreciate brevity, here’s a one-liner <a href="https://blog.finxter.com/how-to-filter-in-python-using-lambda-functions/" data-type="post" data-id="2976">lambda function</a> that performs the check using the modulus operator.</p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">is_even = lambda num: num % 2 == 0

print(is_even(2))  # The smallest even prime.
print(is_even(3))  # And its odd counterpart.</pre>



<p>Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False</pre>



<p>This compact version utilizes a lambda function to perform the same operation as in Method 1. It remains concise and to the point, ideal for quick inline use without defining a full function.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>



<ul class="wp-block-list">
<li><strong>Method 1: Modulus Operator.</strong> Strengths: Intuitive and straightforward to understand. Weaknesses: Possibly less efficient than bit manipulation.</li>



<li><strong>Method 2: Bitwise AND.</strong> Strengths: Fast operation at the bit level. Weaknesses: Less readable for those who are not familiar with bitwise operations.</li>



<li><strong>Method 3: Division and Multiplication.</strong> Strengths: Avoids the use of modulus, potentially offering performance benefits. Weaknesses: More arithmetic operations which may not be as efficient as other methods.</li>



<li><strong>Method 4: Float Division.</strong> Strengths: Offers a different approach that is clear in intent. Weaknesses: Involves floating-point arithmetic, which may be slower and could introduce floating-point precision issues.</li>



<li><strong>Method 5: Lambda One-Liner.</strong> Strengths: Very concise, ideal for quick functional programming usage. Weaknesses: Lambda functions can be less accessible to those less experienced with Python, potentially impacting readability.</li>
</ul>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/11-ways-to-create-a-list-of-even-numbers-in-python/">11 Ways to Create a List of Even Numbers in Python</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-check-if-number-is-even-in-python/">5 Best Ways to Check If Number Is Even in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-23 11:35:59 by W3 Total Cache
-->