<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged advanced-python</title>
<link>https://coderlegion.com/tag/advanced-python</link>
<description>Powered by Question2Answer</description>
<item>
<title>ThreeDimensions Version-1.0.0 is here !</title>
<link>https://coderlegion.com/12471/threedimensions-version-1-0-0-is-here</link>
<description>&lt;h2 id=&quot;threedimensions&quot;&gt;ThreeDimensions&lt;/h2&gt;
&lt;p&gt;Version-1.0.0 Repo - &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/LegedsDaD/ThreeDimensions-v1.1.1&quot;&gt;https://github.com/LegedsDaD/ThreeDimensions-v1.1.1&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;ThreeDimensions is a programmable 3D modeling library for Python, backed by a C++ geometry kernel for heavy mesh operations.&lt;/p&gt;
&lt;p&gt;Do check out &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/LegedsDaD/ThreeDimensions&quot;&gt;Main Repository&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;send-your-creations-using-threedimensions-in-models-by-filling-in-the-form-the-best-models-will-be-added-to-the-examples-of-threedimensions-others-will-be-added-to-the-models-groups-see-current-submissions-in-submissions-do-participate-&quot;&gt;Send your creations using ThreeDimensions in &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/LegedsDaD/Models&quot;&gt;Models&lt;/a&gt; by filling in the &lt;a rel=&quot;nofollow&quot; href=&quot;https://forms.gle/Z8WpocwLCv92MZU17&quot;&gt;Form&lt;/a&gt;. The best models will be added to the examples of ThreeDimensions. Others will be added to the models groups. See current submissions in &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/LegedsDaD/Models/blob/main/README.md&quot;&gt;Submissions&lt;/a&gt;. Do participate !&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Version: 1.0.0&lt;/strong&gt;&lt;/p&gt;
&lt;h3 id=&quot;overview&quot;&gt;Overview&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Python-first API (&lt;code&gt;import threedimensions as td&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;C++ core for mesh math/topology/modifiers when available&lt;/li&gt;
&lt;li&gt;Pure-Python fallback so the package remains usable without compiling native code&lt;/li&gt;
&lt;li&gt;Half-edge/topology-oriented editing workflow with sculpt, modifiers, curves, nodes, UV tools, and export&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;feature-highlights&quot;&gt;Feature Highlights&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Transform system: move/rotate/scale, pivot modes, snapping, mirror transform, proportional falloff&lt;/li&gt;
&lt;li&gt;Selection: vertex/edge/face, loop/ring, box/circle/lasso, select similar&lt;/li&gt;
&lt;li&gt;Editing: extrude, inset, bevel, bridge, fill, grid fill, subdivide, loop cut, spin, screw, solidify, wireframe&lt;/li&gt;
&lt;li&gt;Deformation: bend, twist, taper, stretch, shear, warp&lt;/li&gt;
&lt;li&gt;Symmetry: mirror and symmetrize helpers&lt;/li&gt;
&lt;li&gt;Sculpt: draw/clay/inflate/smooth/grab/pinch/crease/mask style brush workflow + filters&lt;/li&gt;
&lt;li&gt;Remesh/reduction: voxel remesh, quad remesh, decimate&lt;/li&gt;
&lt;li&gt;Primitives: cube, sphere, UV sphere, icosphere, cylinder, cone, torus, plane, grid&lt;/li&gt;
&lt;li&gt;Curves: Bezier, NURBS-style fallback, lathe, curve-to-mesh&lt;/li&gt;
&lt;li&gt;UV: unwrap, smart UV project, project from view, seams&lt;/li&gt;
&lt;li&gt;Retopo helpers: shrinkwrap, poly build, relax topology&lt;/li&gt;
&lt;li&gt;Modifier stack: subdivision, mirror, array, solidify, boolean, decimate, lattice&lt;/li&gt;
&lt;li&gt;Procedural NodeGraph API&lt;/li&gt;
&lt;li&gt;Optional OpenGL viewer (&lt;code&gt;td.viewer(mesh)&lt;/code&gt; or &lt;code&gt;with td.viewer() as scene&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;installation&quot;&gt;Installation&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install pip install threedimensions==1.1.1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Optional viewer dependencies:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install glfw PyOpenGL
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;quick-start&quot;&gt;Quick Start&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import threedimensions as td

mesh = td.create_cube(1.0)
mesh.extrude(distance=0.2)
mesh.bevel(width=0.05)
mesh.subdivide(1)
mesh.save(&quot;model.obj&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;geometry-nodes-programmable-&quot;&gt;Geometry Nodes (Programmable)&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import threedimensions as td

graph = td.NodeGraph()
cube = graph.node(&quot;Cube&quot;, size=1.0)
subdiv = graph.node(&quot;Subdivision&quot;, levels=2)
extrude = graph.node(&quot;Extrude&quot;, distance=0.25)

graph.connect(cube, subdiv)
graph.connect(subdiv, extrude)

mesh = graph.evaluate()
mesh.save(&quot;graph.obj&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;viewer&quot;&gt;Viewer&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import threedimensions as td

mesh = td.create_torus()
td.viewer(mesh)  # blocking preview

with td.viewer() as scene:
    scene.update(mesh)
    scene.run()
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;architecture&quot;&gt;Architecture&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;python/threedimensions/&lt;/code&gt;: high-level Python API wrappers, fallback implementations, procedural nodes, viewer&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;license&quot;&gt;License&lt;/h3&gt;
&lt;p&gt;MIT&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12471/threedimensions-version-1-0-0-is-here</guid>
<pubDate>Sun, 08 Mar 2026 05:38:07 +0000</pubDate>
</item>
<item>
<title>Python: An Expert-Level Deep Dive into Design, Internals, and Ecosystem</title>
<link>https://coderlegion.com/11449/python-an-expert-level-deep-dive-into-design-internals-and-ecosystem</link>
<description>&lt;h2 id=&quot;python-an-expert-level-deep-dive-into-design-internals-and-ecosystem&quot;&gt;Python: An Expert-Level Deep Dive into Design, Internals, and Ecosystem&lt;/h2&gt;
&lt;h3 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Python is a high-level, interpreted, dynamically typed programming language known for its readability and expressive power. Created by &lt;strong&gt;Guido van Rossum&lt;/strong&gt; in 1991, Python has evolved from a scripting language into one of the most dominant technologies in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Artificial Intelligence &amp;amp; Machine Learning  &lt;/li&gt;
&lt;li&gt;Data Science  &lt;/li&gt;
&lt;li&gt;Web Development  &lt;/li&gt;
&lt;li&gt;Automation  &lt;/li&gt;
&lt;li&gt;Cybersecurity  &lt;/li&gt;
&lt;li&gt;DevOps  &lt;/li&gt;
&lt;li&gt;Scientific Computing  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Python’s philosophy emphasizes &lt;strong&gt;simplicity, clarity, and developer productivity&lt;/strong&gt;, while its ecosystem supports enterprise-scale systems.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;2-philosophy-and-design-principles&quot;&gt;2. Philosophy and Design Principles&lt;/h3&gt;
&lt;p&gt;Python’s design is guided by the &lt;strong&gt;Zen of Python&lt;/strong&gt; (&lt;code&gt;import this&lt;/code&gt;):&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&quot;Simple is better than complex.&quot;&lt;br&gt;
&quot;Readability counts.&quot;&lt;br&gt;
&quot;There should be one—and preferably only one—obvious way to do it.&quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4 id=&quot;core-design-features&quot;&gt;Core Design Features&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dynamic typing  &lt;/li&gt;
&lt;li&gt;Automatic memory management  &lt;/li&gt;
&lt;li&gt;Interpreted execution  &lt;/li&gt;
&lt;li&gt;High-level data structures  &lt;/li&gt;
&lt;li&gt;Extensive standard library  &lt;/li&gt;
&lt;li&gt;Multi-paradigm support (OOP, functional, procedural)  &lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;3-python-architecture-and-execution-model&quot;&gt;3. Python Architecture and Execution Model&lt;/h3&gt;
&lt;h4 id=&quot;3-1-cpython-implementation&quot;&gt;3.1 CPython Implementation&lt;/h4&gt;
&lt;p&gt;The reference implementation of Python is &lt;strong&gt;CPython&lt;/strong&gt;, written in C.&lt;/p&gt;
&lt;p&gt;Execution flow:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Source Code (.py)
        ↓
Bytecode Compilation (.pyc)
        ↓
Python Virtual Machine (PVM)
        ↓
Execution
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Python compiles source code into bytecode  &lt;/li&gt;
&lt;li&gt;Bytecode is executed by the Python Virtual Machine  &lt;/li&gt;
&lt;li&gt;This abstraction ensures portability  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;3-2-global-interpreter-lock-gil-&quot;&gt;3.2 Global Interpreter Lock (GIL)&lt;/h4&gt;
&lt;p&gt;The &lt;strong&gt;GIL&lt;/strong&gt; ensures that only one thread executes Python bytecode at a time.&lt;/p&gt;
&lt;p&gt;Implications:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;CPU-bound threading is limited  &lt;/li&gt;
&lt;li&gt;I/O-bound threading performs well  &lt;/li&gt;
&lt;li&gt;Multiprocessing is preferred for parallel CPU tasks  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from multiprocessing import Process

def task():
    print(&quot;Running in parallel&quot;)

if __name__ == &quot;__main__&quot;:
    p = Process(target=task)
    p.start()
    p.join()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;4-data-model-and-object-system&quot;&gt;4. Data Model and Object System&lt;/h3&gt;
&lt;p&gt;Everything in Python is an &lt;strong&gt;object&lt;/strong&gt;, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Functions  &lt;/li&gt;
&lt;li&gt;Classes  &lt;/li&gt;
&lt;li&gt;Modules  &lt;/li&gt;
&lt;li&gt;Integers  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;4-1-object-structure-simplified-&quot;&gt;4.1 Object Structure (Simplified)&lt;/h4&gt;
&lt;p&gt;Each Python object contains:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reference count  &lt;/li&gt;
&lt;li&gt;Type information  &lt;/li&gt;
&lt;li&gt;Value  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;a = 10
b = a
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; reference the same object until reassignment.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;5-advanced-data-structures&quot;&gt;5. Advanced Data Structures&lt;/h3&gt;
&lt;h4 id=&quot;5-1-built-in-collections&quot;&gt;5.1 Built-in Collections&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;list&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;tuple&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;set&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;dict&lt;/code&gt;  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;5-2-time-complexity-average-&quot;&gt;5.2 Time Complexity (Average)&lt;/h4&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Operation &lt;/th&gt;&lt;th&gt;List &lt;/th&gt;&lt;th&gt;Dict &lt;/th&gt;&lt;th&gt;Set&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Lookup     &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;O(1)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Insert     &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;O(1)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Delete     &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;O(1)&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h4 id=&quot;5-3-comprehensions&quot;&gt;5.3 Comprehensions&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;squares = [x*x for x in range(10)]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Set and dictionary comprehensions:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;unique = {x for x in range(10)}
mapping = {x: x*x for x in range(5)}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;6-functions-as-first-class-objects&quot;&gt;6. Functions as First-Class Objects&lt;/h3&gt;
&lt;p&gt;Functions can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Be assigned to variables  &lt;/li&gt;
&lt;li&gt;Be passed as arguments  &lt;/li&gt;
&lt;li&gt;Return other functions  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def decorator(func):
    def wrapper():
        print(&quot;Before execution&quot;)
        func()
        print(&quot;After execution&quot;)
    return wrapper
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;7-decorators-and-metaprogramming&quot;&gt;7. Decorators and Metaprogramming&lt;/h3&gt;
&lt;h4 id=&quot;7-1-decorators&quot;&gt;7.1 Decorators&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;@decorator
def greet():
    print(&quot;Hello&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;7-2-metaclasses&quot;&gt;7.2 Metaclasses&lt;/h4&gt;
&lt;p&gt;Metaclasses control class creation.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class Meta(type):
    def __new__(cls, name, bases, attrs):
        attrs['id'] = 123
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

print(MyClass.id)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;8-concurrency-and-asynchronous-programming&quot;&gt;8. Concurrency and Asynchronous Programming&lt;/h3&gt;
&lt;h4 id=&quot;8-1-threading-vs-multiprocessing&quot;&gt;8.1 Threading vs Multiprocessing&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Threading → I/O-bound tasks  &lt;/li&gt;
&lt;li&gt;Multiprocessing → CPU-bound tasks  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;8-2-asyncio&quot;&gt;8.2 Asyncio&lt;/h4&gt;
&lt;p&gt;Python supports asynchronous programming with &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import asyncio

async def main():
    await asyncio.sleep(1)
    print(&quot;Async execution&quot;)

asyncio.run(main())
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;9-memory-management&quot;&gt;9. Memory Management&lt;/h3&gt;
&lt;p&gt;Python uses:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reference counting  &lt;/li&gt;
&lt;li&gt;Generational garbage collection  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can inspect reference counts:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import sys
a = []
print(sys.getrefcount(a))
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;10-type-hinting-and-static-analysis&quot;&gt;10. Type Hinting and Static Analysis&lt;/h3&gt;
&lt;p&gt;Python supports gradual typing.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def add(a: int, b: int) -&amp;gt; int:
    return a + b
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;mypy&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;pyright&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;pylance&lt;/code&gt;  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Type hints improve maintainability in large systems.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;11-c-extensions-and-performance-optimization&quot;&gt;11. C Extensions and Performance Optimization&lt;/h3&gt;
&lt;h4 id=&quot;11-1-using-c-with-python&quot;&gt;11.1 Using C with Python&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;CPython API  &lt;/li&gt;
&lt;li&gt;Cython  &lt;/li&gt;
&lt;li&gt;ctypes  &lt;/li&gt;
&lt;li&gt;cffi  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;11-2-performance-techniques&quot;&gt;11.2 Performance Techniques&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Use built-in functions  &lt;/li&gt;
&lt;li&gt;Prefer generators  &lt;/li&gt;
&lt;li&gt;Use NumPy for numerical tasks  &lt;/li&gt;
&lt;li&gt;Avoid unnecessary object creation  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example generator:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def count():
    n = 0
    while True:
        yield n
        n += 1
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;12-python-in-large-scale-systems&quot;&gt;12. Python in Large-Scale Systems&lt;/h3&gt;
&lt;p&gt;Python powers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Instagram (Django)  &lt;/li&gt;
&lt;li&gt;YouTube backend  &lt;/li&gt;
&lt;li&gt;Netflix automation systems  &lt;/li&gt;
&lt;li&gt;OpenAI research tools  &lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;popular-frameworks&quot;&gt;Popular Frameworks&lt;/h4&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Domain &lt;/th&gt;&lt;th&gt;Framework&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Web &lt;/td&gt;&lt;td&gt;Django, Flask, FastAPI&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Data Science &lt;/td&gt;&lt;td&gt;Pandas, NumPy&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;ML &lt;/td&gt;&lt;td&gt;TensorFlow, PyTorch&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Automation &lt;/td&gt;&lt;td&gt;Selenium&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;CLI Tools &lt;/td&gt;&lt;td&gt;Click, Typer&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h3 id=&quot;13-packaging-and-dependency-management&quot;&gt;13. Packaging and Dependency Management&lt;/h3&gt;
&lt;p&gt;Modern tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pip&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;venv&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;poetry&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;pipenv&lt;/code&gt;  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;python -m venv env
source env/bin/activate
pip install requests
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;14-testing-and-quality-assurance&quot;&gt;14. Testing and Quality Assurance&lt;/h3&gt;
&lt;p&gt;Testing frameworks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;unittest&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;pytest&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;&lt;code&gt;hypothesis&lt;/code&gt;  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def test_add():
    assert add(2, 3) == 5
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;15-security-considerations&quot;&gt;15. Security Considerations&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Avoid &lt;code&gt;eval()&lt;/code&gt; on untrusted input  &lt;/li&gt;
&lt;li&gt;Use virtual environments  &lt;/li&gt;
&lt;li&gt;Keep dependencies updated  &lt;/li&gt;
&lt;li&gt;Use secure hashing (&lt;code&gt;hashlib&lt;/code&gt;, &lt;code&gt;bcrypt&lt;/code&gt;)  &lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;16-the-future-of-python&quot;&gt;16. The Future of Python&lt;/h3&gt;
&lt;p&gt;Ongoing improvements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Performance optimizations in Python 3.12+  &lt;/li&gt;
&lt;li&gt;Better concurrency models  &lt;/li&gt;
&lt;li&gt;Static typing improvements  &lt;/li&gt;
&lt;li&gt;Faster CPython interpreter  &lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;17-conclusion&quot;&gt;17. Conclusion&lt;/h3&gt;
&lt;p&gt;Python is not merely a scripting language — it is a &lt;strong&gt;general-purpose, high-performance, multi-paradigm ecosystem&lt;/strong&gt; capable of powering:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Enterprise backends  &lt;/li&gt;
&lt;li&gt;AI systems  &lt;/li&gt;
&lt;li&gt;Robotics  &lt;/li&gt;
&lt;li&gt;Embedded applications  &lt;/li&gt;
&lt;li&gt;Scientific simulations  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Its simplicity lowers entry barriers, while its extensibility allows expert-level system design.&lt;/p&gt;
&lt;p&gt;Python succeeds because it optimizes for what matters most:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Developer productivity + Ecosystem power + Readability + Scalability&lt;/p&gt;
&lt;/blockquote&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/11449/python-an-expert-level-deep-dive-into-design-internals-and-ecosystem</guid>
<pubDate>Wed, 11 Feb 2026 11:51:15 +0000</pubDate>
</item>
<item>
<title>Always Five Trick → Class always returns 5 no matter what when you use len().</title>
<link>https://coderlegion.com/5920/always-five-trick-class-always-returns-5-no-matter-what-when-you-use-len</link>
<description>&lt;pre&gt;&lt;code&gt;class AlwaysFive:
    def __len__(self):
        return 5

a = AlwaysFive()
print(len(a))  # Always prints 5
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/5920/always-five-trick-class-always-returns-5-no-matter-what-when-you-use-len</guid>
<pubDate>Thu, 02 Oct 2025 15:38:12 +0000</pubDate>
</item>
<item>
<title>SignBrige: Hands speak. We translate</title>
<link>https://coderlegion.com/3393/signbrige-hands-speak-we-translate</link>
<description>&lt;p&gt;Communication is a basic human right, yet millions of people in the deaf and hard-of-hearing community face barriers every day—especially in virtual spaces, education, and public services.&lt;/p&gt;
&lt;p&gt;As a passionate developer and advocate for inclusive technology, I created SignBridge, an AI-powered system designed to bridge this gap by translating American Sign Language (ASL) into spoken language and vice versa in real time. What began as a local prototype has now grown into a complete solution that can be integrated into modern communication tools like Zoom, Google Meet, or Microsoft Teams—making digital conversations truly accessible.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SignBridge uses a dual-frame video interface:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Frame 1 (Special User): Detects ASL signs using OpenCV and MediaPipe for real-time hand tracking and gesture recognition. The system interprets signs (letters, numbers, phrases) and displays the translated message in the other user's frame.&lt;/p&gt;
&lt;p&gt;Frame 2 (Normal User): Uses speech recognition to convert spoken language into text, and then displays a corresponding ASL image or animation so the deaf/hard-of-hearing user can understand the message visually.&lt;/p&gt;
&lt;p&gt;All of this is powered by a deep learning model trained on a public Kaggle ASL dataset, which ensures recognition of the full ASL alphabet, common numbers, and key phrases.&lt;/p&gt;
&lt;p&gt; Key Features&lt;/p&gt;
&lt;p&gt;Real-time ASL hand sign detection using MediaPipe + OpenCV&lt;/p&gt;
&lt;p&gt;Voice-to-ASL image translation using speech recognition&lt;/p&gt;
&lt;p&gt;ASL alphabet, numbers, and basic phrase recognition&lt;/p&gt;
&lt;p&gt;Dual-frame interface for bidirectional communication&lt;/p&gt;
&lt;p&gt;Backend REST API to power web and mobile platforms&lt;/p&gt;
&lt;p&gt;Future support for integration with Zoom, Meet, and Teams&lt;/p&gt;
&lt;p&gt;Cross-platform design: currently building a web app and mobile app&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://signbridge-pi.vercel.app/&quot;&gt;Checkout the Landing Page&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://youtu.be/ZGcrmh4Sz3U?si=FZVMTUCIASFwmkSx&quot;&gt;See a demo&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Screenshots / Demos&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Get Involved&lt;br&gt;
Want to help make communication more inclusive? Here's how you can contribute:&lt;/p&gt;
&lt;p&gt;Test the beta version on web or mobile (coming soon)&lt;/p&gt;
&lt;p&gt;Suggest improvements or new features (e.g., gesture training, multilingual support)&lt;/p&gt;
&lt;p&gt;Raise awareness about accessibility in tech&lt;/p&gt;
&lt;p&gt;Feel free to reach out if you're interested in collaboration, testing, or integration ideas.&lt;/p&gt;
</description>
<category>AI &amp; Machine Learning</category>
<guid isPermaLink="true">https://coderlegion.com/3393/signbrige-hands-speak-we-translate</guid>
<pubDate>Sun, 22 Jun 2025 03:24:43 +0000</pubDate>
</item>
<item>
<title>Advanced Python Concepts - Metaprogramming</title>
<link>https://coderlegion.com/406/advanced-python-concepts-metaprogramming</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Imagine writing a Python code that can &lt;strong&gt;modify itself or dynamically generate new code&lt;/strong&gt; based on the real-time data input. Metaprogramming is a powerful and advanced technique of programming that allows developers to write code that can manipulate other code and &lt;strong&gt;generate new code during runtime&lt;/strong&gt;. Like we say, metadata is data of data, and metaprogramming is also about writing code that manipulates code. Therefore, this article discusses metaprogramming capabilities to enhance code efficiency and flexibility. We will learn about its foundation, decorators, metaclasses, and dynamic code execution by providing practical examples of each concept. Let's get started!&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Understanding Metaprogramming&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Metaprogramming And Its Role In Python&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In Python, metaprogramming is about writing computer programs that will &lt;strong&gt;assist in writing and manipulating other programs&lt;/strong&gt;. This technique allows programs to treat other programs as data. It generates the code, modifies the existing code, and creates a new programming construct at runtime.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Metaprogramming And Regular Programming&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Before moving on to the technical aspects of metaprogramming concepts, let us first see how generic or regular programming that is based on procedural steps differs from advanced programming concept.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7933413141997827951&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 3. Benefits And Risks Of Using Metaprogramming&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Metaprogramming provides us with a range of benefits. Let's explore them to understand their advantage in the development process.&lt;/p&gt; 
&lt;ol&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Metaprogramming reduces development time by allowing programs to modify themselves at runtime. This technique enables developers to write less code, making the overall development process more efficient compared to traditional software development methods.&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; It provides &lt;strong&gt;solutions to code repetition and reduces the coding time&lt;/strong&gt;. As we know, metaprogramming is all about reducing the code from the developer end and creating an automated way of generating code at run time.&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The programs adapt their behavior dynamically at runtime in response to certain conditions and input data. This makes the software program more powerful and flexible.&lt;/li&gt; 

&lt;/ol&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Similar to the benefits, metaprogramming also comes with some drawbacks as well, which the developer keeps in mind before using this technique.&lt;/p&gt; 
&lt;ol&gt; 
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;One risk of metaprogramming is its complicated syntax.&lt;/li&gt; 
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; As the code is generated dynamically at runtime, there comes the issue of invisible bugs. The bugs come from the generated code, which is challenging to track and resolve. Sometimes, it becomes difficult to find the source and cause of the bug.&lt;/li&gt; 
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; The execution of the computer program takes longer than usual because Python executes the new metaprogramming code at run time.&lt;/li&gt; 
&lt;/ol&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Metaclasses: The Foundation Of Metaprogramming&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Metaclasses A Mechanism For Creating Classes Dynamically&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; A metaclass defines the behavior and structure of classes. Using metaclasses in Python, you can easily customize class creation and behavior. This is possible because Python represents everything, including the classes, as an object. Moreover, the object is created using the class. Therefore, this supposed &quot;class&quot; is act as a child class of another class that is metaclass a super class. In addition, all Python classes are child classes of metaclasses.&lt;/p&gt; 
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2400629546240526351&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Type is the default metaclass in python. It is used to create classes dynamically. 
&lt;/span&gt; 
&lt;/div&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Metaclass ‘__new__’ And ‘__init__’ Methods&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In Python, metaclasses are by default &quot;type&quot; class i.e. base class which is used to manage the creation and behavior of classes. Upon creating the class in Python, we indirectly used the &quot;type&quot; class. The metaclass consists of two primary methods: __new__ and __init__. The __new__ method is used for creating a new object. This method creates and returns the instance, which is then passed to the __init__ method for initialization. It is called before the __init__ method and assures the control creation of the class itself. Then, the __init__ method is used after the creation of new class to initialized it with furthur attribute and methods. This method is quite different from the regular programming method. It allows us to modify and set the class-level attributes after class creation.&lt;/p&gt; 
&lt;div class=&quot;div-green&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt; __new__ and __init__ methods are used for creating the custom classes and its behavior 
&lt;/span&gt; 
&lt;/div&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 3. Example: Creating Custom Metaclasses To Customize Class Creation Behavior&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Let's understand with a simple python example how we can create custom metaclasses to customize the class creation and its behavior using the metaclass primary methods __new__ and __init__.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;# Define the metaclass
class Meta(type):
    #define the new method for creating the class instance
    #cls: metaclass whose instance is being created
    #name: name of the class #base: means the base class
    #class_dict: represent the dictionary of attributes for a class
    def __new__(cls, name, bases, attrs):
        #making the attributes(method) name as upper case
        uppercase_attrs = {key.upper(): value for key, value in attrs.items() if not key.startswith('__')}
        new_class = super().__new__(cls, name, bases, uppercase_attrs)
        print(&quot;Class {name} has been created with Meta&quot;)
        return new_class
    
    #the class is initialized
    def __init__(cls, name, bases, dct):
        super().__init__(name, bases, dct)
        print(f&quot;Class {name} initilized with Meta&quot;)
    
# Using the metaclass in a new class
class MyClass(metaclass=Meta):    
    def my_method(self):
        print(f&quot;Hello!&quot;)

# Instantiate MyClass and access its custom attribute
obj = MyClass()
#here the attribute of the class is change into uppercase i.e. the name of method
obj.MY_METHOD()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4737028447708648130&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Remember that in the output, the &quot;Hello&quot; string will not be converted into uppercase, but the method name 'my_method'  as 'MY_METHOD' that will print the string. This means that we are converting the name of the method into uppercase.
&lt;/span&gt; 
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Decorators: Metaprogramming At The Function Level&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Decorators As Functions That Modify The Behavior Of Other Functions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/206/decorators-in-python-with-examples?show=206#q206&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;Decorators&lt;/a&gt; are the key features of Python metaprogramming. Decorators are a powerful feature that allows developers to modify existing code without changing the original source code. It allows you to add new functionality by extending the existing function. Decorators are typically performed on functions, and their syntax uses the “@” symbol with the decorator function name before its code. In Python, decorators act as a wrapper around other functions and classes. The input and output of the decorator are the function itself, typically executing functionality before and after the original function. &lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Syntax Of Decorators&lt;/h3&gt;  
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Decorators use the @decorator_name as a syntax. Whereas the decorator_name is the name of the function that you make as a decorator.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;@decorator_name 
def function_name(): 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The syntax is also used as following, which shows the decorator taking a function as an argument and save the result into another function.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;Function_name = decorator_name(function_name) 
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3.  Illustration of creating and using decorators to add functionality to functions&lt;/h3&gt;  
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Below is an example of using &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/glossary.html#term-decorator&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;decorators&lt;/a&gt; to convert the string of one function into uppercase, which means adding the uppercase functionality to the function:&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#function for converting the string into upercase
def my_decorator(function): 
    #function within a function
    def wrapper(): 
        #here, we call the decorator function inside this function
        func = function() 
        #converting the string
        upper_Case = func.upper() 
        return upper_Case
    return wrapper
    
@my_decorator
def get_String(): #getting the string for converting in upper case
    return &quot;Actions speak louder than words&quot;
print(get_String()) #printing the string
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14358549549047297881&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; The 'inspect' Module: Introspection And Reflection&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Introduction To The `Inspect` Module For Introspection And Reflection&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In the metaprogramming world, inspection and reflection are key terms. Inspection is performed to examine the type and property of an object in a program and provide a report on it at runtime. In contrast, reflection involves modifying the structure and behavior of an object at runtime. These two language features make python a strongly typed dynamic language. We can perform inspection and reflection in metaprogramming using the &quot;inspect&quot; module. This module provides various functions for introspection, including information about the type and property of an object, the source code, and the call stack.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. How To Use The 'inspect' Module To Examine And Modify Objects At Runtime&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Let's understand that using the &quot;inspect&quot; module for introspection and reflection combined with other Python features, we can examine and modify the object at run time in metaprogramming. We will learn it step by step:&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Examine The Object Using &quot;inspect&quot; Module&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;#import inspect module
import inspect

#create a class name person
class Person:
    #setting the class attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    #generating a function
    def greet(self):
        return &quot;Name is {self.name} and Age is {self.age}&quot;

person = Person(&quot;Harry&quot;, 26)

# Get the class of the object
print(&quot;Class of obj:&quot;, inspect.getmembers(person.__class__))

# Retrieve all members of the object
print(&quot;Members of obj:&quot;, inspect.getmembers(person))

#Print the source code
print(&quot;Source code of MyClass:&quot;)
print(inspect.getsource(Person))

#Print the documentation string
print(&quot;Docstring of MyClass:&quot;, inspect.getdoc(Person))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=271972164021681852&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7295861803833424547&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4103018145557150638&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Modifying The Object At Runtime&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;#import inspect module
import inspect
import types

#create a class name person
class Person:
    #setting the class attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    #generating a function
    def greet(self):
        return &quot;Name is {self.name} and Age is {self.age}&quot;

person = Person(&quot;Harry&quot;, 26)

# Add a new attribute
setattr(person, 'new_attribute', 42)
print(&quot;New attribute value:&quot;, person.new_attribute)

# Modify an existing attribute
setattr(person, 'name', &quot;Henry&quot;)
print(&quot;Modified name:&quot;, person.name)

# Add a new method dynamically
def myfunc(self):
    print(&quot;My age is {self.age}&quot;)

setattr(Person, 'myfunc', myfunc)  # Attach the method to the class

# Call the new method
print(&quot;New method output:&quot;)
person.myfunc()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7389399100759712724&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; This is how you can examine and perform modification dynamically at run time. Using the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/inspect.html&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;inspect&lt;/a&gt; module combined with Python's built-in functions like setattr and delattr will allow the developer to write flexible and adaptive that can change at runtime.&lt;/p&gt; 
&lt;div class=&quot;div-green&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Both setattr and delattr are Python functions for dynamically changing object attributes. In these functions, setattr is used to set and alter the attribute, and delattr is used to delete the attribute from an object. 
&lt;/span&gt; 
&lt;/div&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 3. Practical Use Cases For Introspection And Reflection&lt;/h3&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Debugging And Code Analysis&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; As we know, &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/218/writing-to-files-in-python&quot; target=&quot;_blank&quot;&gt;debugging&lt;/a&gt; is quite more hectic and time-consuming than writing the code the first time. Developers debug the code to verify and find the sources of defects to handle them at the early stages. However, it is a very heterogeneous process when we cannot identify its source. Therefore, introspection and reflection are very useful for debugging the code. It examines the object dynamically at run time by providing the details of the object’s nature, including its behavior. It provides the details of object attribute values and unexpected values and explains how the state of the object changes over time. To make this clearer, let's use an example.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#import inspect module
import inspect

#create a class name person
class Person:
    #setting the class attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    #generating a function
    def greet(self):
        return &quot;Name is {self.name} and I am {self.age} years old.&quot;

person = Person(&quot;Harry&quot;, 26)

# inspecting attribute
print(&quot;Object Attribute:&quot;, dir(person))
print(&quot;Value of Attribute:&quot;, person.name, person.age)

#Add new attribute for debugging
setattr(person, 'debug_info', &quot;Henry&quot;)
#print debug info like this
print(&quot;Debug Info&quot;, person.debug_info)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10726686027779450202&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;To sum up, we discussed the Python advanced concept, which is metaprogramming. As we know, metaprogramming is the techniques that &lt;strong&gt;extend and modify the behavior of the Python language&lt;/strong&gt; itself. It can help you write &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/182/python-functions&quot; target=&quot;_blank&quot;&gt;functions&lt;/a&gt; that can modify and generate other functions.. We can perform metaprogramming using different approaches like metaclasses allows us to use the default type class and then the decorator, which acts as the wrapper to another function and shifts towards the techniques to debug the code beforehand. So, wherever you are moving towards Python advanced concepts, do not forget to learn about metaprogramming significance as well. I hope this guide is helpful to you. Thank you for reading. Happy coding!&lt;/p&gt; 
&lt;hr&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Additional Reference&lt;/h2&gt;   
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/inspect.html&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;Python Inspect Module&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/datamodel.html#metaclasses&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;MetaClasses in Python&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/glossary.html#term-decorator&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;Decorators&lt;/a&gt;&lt;/p&gt;
</description>
<category>Miscellenous</category>
<guid isPermaLink="true">https://coderlegion.com/406/advanced-python-concepts-metaprogramming</guid>
<pubDate>Thu, 10 Oct 2024 20:40:24 +0000</pubDate>
</item>
<item>
<title>Advanced Python Concepts - Networking with Python</title>
<link>https://coderlegion.com/403/advanced-python-concepts-networking-with-python</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Have you ever wondered how your &lt;strong&gt;device is connected over the Internet&lt;/strong&gt;? Or how the business manages to &lt;strong&gt;share information across regions&lt;/strong&gt; seamlessly? All this is achieved using &lt;strong&gt;computer networks&lt;/strong&gt; as part of the business strategy. It allows us to establish communication, collaborate, and share resources among different applications and devices in the network over the Internet. Now, you can contact or share things with your friends or anyone with just one click, thanks to the integration of networking with software applications, and various other technologies. In Python, networking is a fundamental concept that &lt;strong&gt;enables the interaction between devices&lt;/strong&gt; and external resources. Python includes many built-in modules that support networking capabilities, such as `socket` for general networking and `requests` for HTTP communication. &lt;br&gt; Therefore, in this article, we will discuss networking from its basic concepts to advanced concepts in Python using practical examples.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Introduction to Networking Concepts&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Networking and Its Significance In Distributed Systems&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Networking involves connecting multiple computers and devices via wired cables or wireless networks to exchange data and share resources over the Internet. It allows communication between multiple devices. As we know, distributed systems are those in which large numbers of clients, hardware devices, and processes are connected to share resources and communicate. Therefore, networking and distributed systems are significantly interconnected. They provide the infrastructure that facilitates storage, resource sharing, and electronic communication to enhance the efficiency and productivity of the system.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Key Networking Concepts&lt;/h3&gt;  
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Some key networking concepts that we use in our day-to-day lives are as follows:&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2.1. IP Address&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; An IP address uniquely identifies your device on a network. If you have a device that connects to the Internet, it must have an IP address. IP stands for &lt;strong&gt;Internet protocol&lt;/strong&gt;. It is a unique number or an identifier for the computer or device within the network. Every device would have a unique number that makes it different from the other devices within the network. For example:&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;IPv4: 32-bit address: 192.168.1.1 
IPv6: 128-bit address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-blue&quot;&gt;   
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;   
&lt;span class=&quot;alert-body&quot;&gt; An IP address is a unique string of numbers separated by full stops that identifies each computer that uses the Internet protocol to communicate over a network. 
&lt;/span&gt;  
&lt;/div&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2.2. Port&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; A port is a numerical identifier used in networking to specify a particular service or process on a device. In contrast with an IP address, which identifies the location of a device on a network, ports allow multiple services to operate concurrently on the same device. It ensures that data is directed to the correct application or process. These ports are ranges from &lt;strong&gt;0 to 65535&lt;/strong&gt;, having certain scale reserved for specific protocols. For example:&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;HTTP uses port 80  
HTTPS uses port 443
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2.3. Protocol&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; A network protocol is a set of procedures and practices for communication between network devices. It defines how data are formatted, transmitted, and received. Examples include &lt;strong&gt;HTTP, FTP, SMTP, and DNS&lt;/strong&gt;. Protocols can operate at various layers in the OSI model, such as the application layer (HTTP), transport layer (TCP), and network layer (IP).&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2.4. Sockets&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; A socket is a network endpoint for sending or receiving data across multiple devices. It involves a pairing of an &lt;strong&gt;IP address and a port number&lt;/strong&gt;. Sockets can be of two main types: &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/socket.html#socket.SOCK_STREAM&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt; SOCK_STREAM&lt;/a&gt; for TCP connections, which are connection-oriented, and &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/socket.html#socket.SOCK_DGRAM&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;SOCK_DGRAM&lt;/a&gt; for UDP connections, which are connectionless. Sockets enable the implementation of various network services, such as web and email servers.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 3. OSI Model and The TCP/IP Stack&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Certain models are defined that tell us how to connect our devices or computers over the Internet so that they can interact and communicate with each other. There are two primary models for defining networking. &lt;strong&gt;OSI model or TCP/IP stack&lt;/strong&gt;. Let us get an overview of each of them briefly:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2316216321651093246&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3.1. TCP/IP Stack&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;The TCP/IP stack is a suite of communication protocols used to interconnect network devices on the Internet, ensuring reliable data transmission and communication. It is a set of procedures on how computers can interact and how to design those systems. To understand the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/182/python-functions&quot; target=&quot;_blank&quot;&gt;functions&lt;/a&gt;, it is divided into five layers. Each layer has its work, and these are the Application, Transport, Network Access, Data Link, and Physical layers. The TCP/IP stack provides a practical implementation of networking in the real world in contrast with the OSI model, which provides a theoretical understanding of networking communication. In addition, the Transport layer provides the facility for reliable data transmission, and Network Access ensures the correct IP address and routing of data packets, and so on.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3.2. OSI Model&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Similar to TCP/IP, the OSI model is also used to design the network across multiple devices. It is a conceptual framework consisting of a set of procedures for understanding and implementing network protocols in seven different layers. It shares the same layer as TCP/IP, with an additional layer. These includes: Application, Presentation, Session, Transport, Network Access, Data Link, and Physical Layer. Specifically, the main difference between OSI and TCP/IP is the two additional layers molded into the application layer of TCP/IP.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Socket Programming Basics&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Socket Programming As The Foundation Of Networking In Python&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Networking involves the connection of two or more devices such that communication is possible within them. In Python, sockets programming is a fundamental and core network creation mechanism. For socket programming, we need to import the socket module. Using the socket module, a developer can generate, configure, and manage sockets for TCP and UDP communication. This module has many built-in methods required for creating sockets and helping them associate with each other. A few important methods that are used are &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/socket.html#socket.socket&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;socket.socket&lt;/a&gt;, which is used to create a socket. This socket is used on both the client and server sides. Moreover, to accept the communication, we use the socket.accept method.&lt;/p&gt; 
&lt;div class=&quot;div-blue&quot;&gt;   
&lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;   
&lt;span class=&quot;alert-body&quot;&gt; TCP stands for transmission control protocol, which is a connection-oriented protocol that ensures reliable data transfer. UDP is a user datagram protocol, a connectionless protocol that prioritizes speed over reliability. 
&lt;/span&gt;  
&lt;/div&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 2. Sockets As Endpoints For Communication Between Machines&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Sockets are the network endpoints used for sending and receiving data. By default, a single network has two sockets, one for each communication device. These sockets combine IP addresses and port numbers. In addition, a single device can have N sockets based on the port number used. Different ports are available for different types of protocols; for example, &lt;strong&gt;HTTP uses port 80&lt;/strong&gt;. Through this endpoint mechanism, developers can ensure an accurate and reliable exchange of data in various networking scenarios.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 3. Example: Creating and Using Sockets for Basic Network Communication&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Now that we have understood what socket programming is as it is the foundation of Python programming, let's move to the code editor and see how we can create it. We must create two different files for the client and server sides to establish the connection.&lt;/p&gt; 
&lt;p&gt;&lt;em&gt;server.py&lt;/em&gt;  &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #Import library

#Create a socket object and then define two arguments first one specifies the IP address
#and second indicate the use of a TCP socket.
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Prepare to receive connections by binding it to the IP address and port
soc.bind((socket.gethostname(), 1042))
#Listen to the connection
soc.listen(5)

while True:
     #Set client socket and address and make a connection
     clt, addr = soc.accept() 
     print(f&quot;Connection Established to address {addr}&quot;)
     msg = &quot;Message Received and the message is -&amp;gt;&quot;
     clt.send(bytes(msg + &quot;Socket Programming in Python&quot;, &quot;utf-8&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7651478305856146658&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;client.py&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #Importing the module

#Create a socket object and then define two arguments first one specifies the IP address
#and second for indicating the use of a TCP socket.
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Set the connection with the port number and hostname
soc.connect((socket.gethostname(), 1042))
#Set the bytes of the message how much you want to receive
msg = soc.recv(100)
print(msg.decode(&quot;utf-8&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16170338199423632630&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Working with TCP/IP&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; 1. Transmission Control Protocol (TCP) And Its Role in Communication&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; TCP, also known as transmission control protocol, is a transport layer protocol within the TCP/IP model. It consists of a set of protocols and procedures that decide how to send data over the Internet. Usually, when data are sent as files, they are broken down into individual packets. When packets arrive at the destination with a unique number for each packet. We can assemble them with it. In addition, if some packets are missing, TCP ensures that they are resend. This is why we call TCP a reliable protocol for communication because it establishes communication through the handshake process, acknowledges the received data, and retransmits lost packets by maintaining the correct order of packets and ensuring data integrity and delivery.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2. Example: Creating TCP Client And Server Applications In Python&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The server is the software that waits for the client's request, and the client requests the resources from the server. Socket programming is mostly implemented for the client-server architecture. Here, we discuss the example of creating a client and a server where the client sends a message, and the server responds to that message and gives the appropriate response to that request using the socket module with TCP. Let us design both the client and server model.&lt;/p&gt; 
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12566771459980424545&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;server.py&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #Import socket library

def start_server():
    #Create a TCP/IP socket
    #Create a socket object and then define two arguments first one specifies the IP
address
    #and second for indicating the use of a TCP socket.
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    #Bind the socket to the port
    server_address = ('localhost', 65432)
    print('Starting server on {} port {}'.format(*server_address))
    server_socket.bind(server_address)

    #Listen for incoming connections
    server_socket.listen(1)

    while True:
        #Wait for a connection
        print('Waiting for a connection')
        connection, client_address = server_socket.accept()
        try:
            print('Connection from', client_address)

            #Receive the data and send it back
            while True:
                data = connection.recv(1024)
                if data:
                    print('Received: {}'.format(data.decode()))
                    connection.sendall(data)
                else:
                    print('No more data from', client_address)
                    break
        finally:
            #Clean up the connection
            connection.close()

if __name__ == '__main__':
    start_server()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4463825682060641409&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;em&gt;client.py&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #import socket library
def start_server():
    #Create a TCP/IP socket
    #Create a socket object and then define two arguments first one specifies the IP address
    #and second for indicating the use of a TCP socket.
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    #Connect the socket to the server's port
    server_address = ('localhost', 65432)
    print('Connecting to {} port {}'.format(*server_address))
    client_socket.connect(server_address)

    try:
        #Send data
        message = 'Hello, Server!'
        print('Sending: {}'.format(message))
        client_socket.sendall(message.encode())

        #Look for the response
        amount_received = 0
        amount_expected = len(message)

        while amount_received &amp;lt; amount_expected:
            data = client_socket.recv(1024)
            amount_received += len(data)
            print('Received: {}'.format(data.decode()))

    finally:
        #Close the socket
        print('Closing socket')
        client_socket.close()

if __name__ == '__main__':
    start_client()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13724177860889782380&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3. Building A Simple Chat Application Using TCP Sockets&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Let us create a simple chat application in Python using TCP sockets, where the server listens to the incoming commands and the client connects to that server to send and receive messages. We are going to build the chat room using the Python built-in module i.e. socket. So, we need to write code for each side like the client and the server, separately:&lt;/p&gt; 
&lt;p&gt;&lt;em&gt;server.py&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #Import library

#Create a socket object and then define two arguments first one specifies the IP address
#and second for  indicating the use of TCP socket.
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Prepare to receive connections by binding it to the IP address and port
soc.bind((socket.gethostname(), 1042))
#Listen the connection
soc.listen(5)
print(&quot;Server listening...&quot;)

#Set client socket and address and make connection
clt, addr = soc.accept() 
print(f&quot;Connection Established to address {addr}&quot;)

try:
    while True:
        data = clt.recv(1024).decode('utf-8')
        if not data:
            break
        print(f&quot;Received from client: {data}&quot;)
        clt.send(&quot;Message received&quot;.encode('utf-8'))
finally:
    clt.close()
    soc.close()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9110115454106627167&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;client.py&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import socket #Importing the module

#Create socket object and then define two arguments first one specifies the IP address
#and second for  indicating the use of TCP socket.
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Set the connection with the port number and hostname
soc.connect((socket.gethostname(), 1042))
#Set the bytes of message how much you wanna receive
try:
    while True:
        message = input(&quot;Enter your message: &quot;)
        soc.send(message.encode('utf-8'))
        data = soc.recv(1042).decode('utf-8')
        print(f&quot;Received from server: {data}&quot;)
finally:
    soc.close()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7141288175814402414&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;Networking&lt;/strong&gt; is a crucial concept in &lt;strong&gt;computer science and programming&lt;/strong&gt;. It resolves most human problems, whether you are working in your office or sharing files with your team. Alternatively, contact a relative from another country. In summary, we focused on the solid introduction of networking foundations using Python. We learned the essential topics of &lt;strong&gt;network controls and models, client and server architecture&lt;/strong&gt;, and practical examples using the &lt;strong&gt;socket library&lt;/strong&gt;. This library ensures the &lt;strong&gt;establishment of a secure and reliable network&lt;/strong&gt; for distributed systems. Keep experimenting and building upon these skills to further enhance your proficiency in network programming. Hope this guide is helpful. Thank you for reading. Happy Coding! &lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Reference&lt;/h2&gt;    
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/ipc.html&quot; target=&quot;_blank&quot;&gt;Networking in Python&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/howto/sockets.html&quot; target=&quot;_blank&quot;&gt;Socket library&lt;/a&gt; &lt;/p&gt;
</description>
<category>Networking</category>
<guid isPermaLink="true">https://coderlegion.com/403/advanced-python-concepts-networking-with-python</guid>
<pubDate>Tue, 08 Oct 2024 09:41:30 +0000</pubDate>
</item>
<item>
<title>Advanced Python Concepts - List Comprehensions</title>
<link>https://coderlegion.com/306/advanced-python-concepts-list-comprehensions</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In Python, we can &lt;strong&gt;construct a &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/184/python-lists&quot; target=&quot;_blank&quot;&gt;list&lt;/a&gt; from another existing list&lt;/strong&gt;. Well, this doesn't sound very impressive, but what if I told you that, we can take all those complex lines of code containing a for loop and an if-else statement? As well as the appending of modified content into a new list? By narrowing it into a single line of code with the help of list comprehension? Without using the append method even once? It is considered a &lt;strong&gt;powerful syntactic feature for creating a concise list&lt;/strong&gt;. It enhances code readability and improves the performance of the program by offering a more optimized method of list creation compared with the traditional method. &lt;br&gt; Therefore, In this article, we will explore list comprehension from its basic understanding, concise and compact syntax in the realm of for-loops, conditional statements, string manipulation, its benefits, and some practical use case examples. &lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Syntactic feature refers to the pre-defined set of rules, syntax, or structure about how datatype, methods, operators, etc, are used to write a valid Python code.
&lt;/span&gt; 
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Understanding List Comprehension&lt;/h2&gt;
&lt;h3 style=&quot;margin-top: 0.5; margin-bottom: 0;&quot;&gt;1. Definition Of List Comprehensions As Concise Expressions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;In Python, list comprehension is a concise method for creating a list. It is defined as the shorter, readable, and compact syntax of creating a list from an existing list. The name used is condensed code for creating the list. The list is surrounded by brackets; however, instead of a list of data, we write an expression followed by loops and if-clauses. &lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2. Syntax and Structure Of The List Comprehensions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.5; margin-bottom: 0;&quot;&gt;The most basic syntax of list comprehension is:&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;list = [expression for item in iterable if condition == true] 
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
  &lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Expression: An expression that produces the elements of the new list.&lt;/li&gt; 
  &lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Item: Variable representing the members of the iterable separately. &lt;/li&gt;
  &lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Iterable: The object used for iterating e.g. range, list, tuple, dictionary.&lt;/li&gt; 
  &lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0px;&quot;&gt;Condition: Optional if-clause to filter items from the iterable.&lt;/li&gt;  
&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3. Benefits Of Using List Comprehensions Over Traditional Loop &lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;List comprehension and traditional for-loop are concepts used to iterate lists in Python, but each has its use case based on the context. List comprehension is more readable and compact than the traditional loop because it is written in a single line of code. Whereas for the traditional for-loop, multiple lines of code are required to achieve the same results. In addition, they are more optimized and efficient in terms of performance, especially for simple iteration operations, than the traditional for-loop. List comprehension also aligns with a functional programming language, but traditional for-loop does not align with this paradigm.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17710198764673098022&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin-top: 0.2; margin-bottom: 0px;&quot;&gt;Basic List Comprehension Syntax&lt;/h2&gt; 
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0px;&quot;&gt;1. Introduction To The Basic Syntax Of List Comprehensions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0px; margin-bottom: 0.5;&quot;&gt;The list comprehension syntax consists of brackets containing the expression followed by the for-loop, with zero or more for-loops or if clauses as a condition. The expression contains any kind of iterable object, such as a list, tuple, or dict, that is evaluated to create a new list without changing the existing list.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9533605750019918226&quot; alt=&quot;&quot;&gt; &lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.5; margin-bottom: 0px;&quot;&gt;2. Illustration Of Simple List Comprehensions For Generating Lists Of Numbers and Strings&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0.5;&quot;&gt;Let's take an example of creating a new list of square numbers from the list of integers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;numbers = [1,2,3,4,6,7,8,9,10] #list of whole numbers
square = [num ** 2 for num in  numbers] #list comprehension in single line
print(square)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15911431196562957192&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0.5;&quot;&gt;Let's take another example of creating a new list of uppercase strings from the existing list of strings with elements in lowercase. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;string  = [&quot;intro&quot;, &quot;to&quot;, &quot;list&quot;, &quot;comprehension&quot;] #list of string
upper_case = [i.upper() for i in string] #list comprehension in single line
print(upper_case)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3310391762347263806&quot; alt=&quot;&quot;&gt; &lt;/p&gt;
&lt;h2 style=&quot;margin-top: 0.1; margin-bottom: 0px;&quot;&gt;Using Conditionals In List Comprehensions&lt;/h2&gt; 
&lt;h3 style=&quot;margin-top: 0; margin-bottom: 0.5;&quot;&gt;1. Explanation Of How To Incorporate Conditional Statements In List Comprehensions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.2px; margin-bottom: 0.5;&quot;&gt;As we understand the basics of &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions&quot; target=&quot;_blank&quot; title=&quot;file&quot;&gt;list comprehension&lt;/a&gt;, let us move toward the advanced concepts. We can also use a conditional statement, i.e., an if-else clause, to filter the elements from the list based on the condition to create a new list. Conditional statements are used to filter the elements or values from the given data. This way, we can create a new list without changing the previous existing list.&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.2; margin-bottom: 0px;&quot;&gt;2. Illustration Of Using if-else Clauses For Filtering Elements In List Comprehensions.&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0.2px; margin-bottom: 0.5;&quot;&gt;Let us illustrate the if-else clause with an example of creating a new list of numbers by filtering even numbers from an existing list.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;numbers = [1,2,3,4,6,7,8,9,10] #list of whole numbers
even_number = [num for num in  numbers if num % 2 == 0] #list comprehension in single line
print(even_number)
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.2px; margin-bottom: 0.5;&quot;&gt;Here is how list comprehension works: &lt;/p&gt; 
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14576780143048311418&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16741714886231116924&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0.5;&quot;&gt;3. Applying Conditional Logic To Create Complex List Comprehensions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.2px; margin-bottom: 0;&quot;&gt;Before demonstrating the example for complex list comprehension, we need to understand that the conditional expression can be used more than once to define the list comprehension and create the new output list. Let us create a new list of squares of even numbers and cubes of odd numbers from the list of integers.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;numbers = [1,2,3,4,6,7,8,9,10] #list of whole numbers
new_list = [num ** 2 if num % 2 == 0 else num ** 3 for num in  numbers] #list comprehension in single line
print(new_list)
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.2px; margin-bottom: 0;&quot;&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; In this example, the list comprehension expression alters the list items into squares if the number is even and cubes if the number is odd. Condition logic is used to filter the even and odd numbers from the list of integers. &lt;/p&gt; 
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16103733672426149223&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Nested List Comprehension&lt;/h2&gt;
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0.5;&quot;&gt;1. Introduction To Nested List Comprehensions For Creating Lists of Lists&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.4px; margin-bottom: 0;&quot;&gt;Besides conditional statements, where we generate the list based on filtering conditions, we can nest list comprehension into other list comprehensions similar to the nested for-loop concept. It is used when each element in the list is itself a list or when we want to convert a list of lists into a single list using flattening techniques. It is a Python technique in which multiple &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#for&quot; target=&quot;_blank&quot; title=&quot;file&quot;&gt;for-loop&lt;/a&gt; or if clauses are used, and by which we embed the list comprehension in another&lt;/p&gt; 
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0.5;&quot;&gt;2. Syntax and Structure Of Nested List Comprehensions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0.4px; margin-bottom: 0.5;&quot;&gt;The syntax of nested list comprehension containing multiple for-loop is as follows:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4104413441066425001&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.4px; margin-bottom: 0;&quot;&gt;Take a look at each component of syntax: &lt;/p&gt;
&lt;ol&gt;   
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;new_list: Name of the new list that would be created.&lt;/li&gt;    
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Expression: The operation or transformation that produces the value of the new list.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Iterable: There are two iterable, inner and outer iterable. Both are a list or other iterable objects you loop over.&lt;/li&gt;  
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0px;&quot;&gt;Item: The elements in the list.&lt;/li&gt;    
&lt;/ol&gt;
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0.5;&quot;&gt;3. Example Of Nested List Comprehensions for Matrix Operations And Data Transformation&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.4px; margin-bottom: 0;&quot;&gt;Let's explore the concept of nested list comprehension with an example of a 2D matrix transpose operation.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;matrix = [[1, 2, 3],  #2d matrix
          [4, 5, 6],
          [7, 8, 9]]
new_matrix = [[row[i] ** 2 for row in matrix] for i in range(3)] # taking matrix transpose and squaring the value
print(new_matrix)
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.4px; margin-bottom: 0;&quot;&gt;In the above code, I created a 2D matrix with some values. List comprehension is then used to contain the two for-loop clauses. In the inner for loop, the expression is defined, which means that the values of the matrix are squared by iterating through the matrix and storing the value in the variable row. The outer loop iterates from 0 to 2 (inclusive), creating a list for each value of i.&lt;/p&gt;  
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=6680034602747213359&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin-top: 0.5px; margin-bottom: 0;&quot;&gt;Practical Use Cases Of List Comprehensions&lt;/h2&gt; 
&lt;h3 style=&quot;margin-top: 0.4px; margin-bottom: 0.5px;&quot;&gt;1. Practical Examples Of List Comprehensions In Everyday Programming Tasks&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.5px; margin-bottom: 0.4px;&quot;&gt;List comprehension is widely popular in Python programming because of its concise, easy-to-readable syntax and its effective performance. It provides us with a compact way of creating the list in a single line without complicating the logic. Now, I will discuss the practical examples detailing how list comprehensions can be applied to common scenarios.&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;1.1. Creating A Simple List Of Integers With Multiples Of 5&lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;numbers = [1,2,3,4,6,7,8,9,10] #list of whole numbers
new_list = [num * 5 for num in  numbers] #list comprehension in single line
print(new_list)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3230589001469622199&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;1.2. Performing Filtering Operations On The List &lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;people_age = [12,17,38,45,56,19,22]
eligibility = [age for age in people_age if age &amp;gt; 18 ] #list for checking eligibility
#prints the result
print(eligibility)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17601161158176542510&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;1.3. Data Manipulation And Transformation Using List Comprehension &lt;/h3&gt; 
&lt;pre&gt;&lt;code&gt;string  = [&quot;how&quot;, &quot;to&quot;, &quot;perform&quot;, &quot;data&quot;, &quot;transformation&quot;] #list of string
upper_case = [i.upper() for i in string] #list comprehension in single line
print(upper_case)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15043044709615181350&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;2. List Comprehensions With Other Python Features&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0px; margin-bottom: 0px;&quot;&gt;List comprehension is also embedded with other Python built-in &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/182/python-functions&quot; target=&quot;_blank&quot;&gt;functions&lt;/a&gt; which include lambda, zip, and enumerate functions. These are:&lt;/p&gt; 
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;1. Zip() Function &lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0px; margin-bottom: 0px;&quot;&gt;The zip() function is used to combine two or more lists into a single list of elements. &lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;list1 = [1,7,8,4,6,9,2]
list2 = [2,5,7,3,7,9,3]
#this zip the two list into one based on the expression
result = [i+j for i, j in zip(list1, list2)]
 #prints the result
print(&quot;The Result is:&quot;,list(result))
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin-top: 0.3px; margin-bottom: 0px;&quot;&gt;2. Enumerate() Function&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0px; margin-bottom: 0px;&quot;&gt;The enumerate() function is used to track the indexing of the elements in the list comprehension. &lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;colors = [&quot;Red&quot;, &quot;Green&quot;, &quot;Black&quot;, &quot;Blue&quot;] #list of colors
new_list = [(index, item) for index, item in enumerate(colors)] #list comprehension with enumerate function
print(new_list)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 style=&quot;margin-top: 0.5px; margin-bottom: 0px;&quot;&gt;Performance Considerations&lt;/h2&gt; 
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0;&quot;&gt;1. Performance Implications Of Using List Comprehensions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;Now, let's move toward the performance considerations, starting with a closer look at the factors and their implications. List comprehension is preferred because of its compact nature and readability. They provide a concise way to generate the list. However, with this significance, there are some considerations as well. These as:&lt;/p&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Talking about performance, list comprehension sometimes hinders the readability of the program. When dealing with larger and more complex logic, writing it into a single line of code makes it difficult to understand, debug, and maintain.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;Memory constraints exist when dealing with a large dataset. It means that the new list consumes a significant amount of memory upon creation before assigning it to the variable, which is problematic compared to generator functions.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0px;&quot;&gt;Using the generator function instead of list comprehension can offer better performance. The generator function does not store the entire list in the memory, rather it only produces an item when requested.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0;&quot;&gt;2. When To Use List Comprehension For Performance Optimization And When To Avoid Them?&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;&lt;strong&gt;When to Use List Comprehension:&lt;/strong&gt; When you have to perform simple operations like data processing, transforming, and filtering of data then list comprehension is mostly favored. It provides a concise way, enhances the code readability, and makes it maintainable, and more expressive than a traditional loop. They are faster in execution and optimized than traditional loops even if the dataset is large. &lt;br&gt;
&lt;strong&gt;When to avoid them:&lt;/strong&gt; When the program has complex logic that cannot be written in a single line of code, then avoid using list comprehension. To reduce the complexity, try using a traditional loop that provides better clarity. &lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0px; margin-bottom: 0;&quot;&gt;3. Comparison Of The Performance Of List Comprehensions With Traditional Loop&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;Let us compare the performance of list comprehension with a traditional loop using a simple Python example. Working with a small dataset will not be an issue for a traditional loop, but the real problem comes when dealing with a larger dataset. List comprehension is more optimized and efficient than traditional for-loops, which makes them memory-efficient and allows faster iteration over larger datasets. Here, I will list half a million random numbers and store them on the num_list variable. Then, we use for-loop and list comprehension to generate a new list having values higher than a quarter of a million. In the end, compare the speed of both approaches using timeit.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import random
import timeit
num_list = random.sample(range(0, 50000), 10000) #generate random numbers
def trad_loop(): #traditional loop approach
    new_list = []
    for num in num_list:
        if num &amp;gt; 25000:
            new_list.append(num)

def comp_list(): #list comprehension approach
    new_list = [num for num in num_list if num &amp;gt; 25000]

#calculating speed
trad_loop_speed = timeit.timeit(trad_loop, number=1000)
comp_list_speed = timeit.timeit(comp_list, number= 1000)
print(&quot;For loop time:&quot;, round(trad_loop_speed * 1e6, 2), &quot;microseconds&quot;) #printing the reault in miliseconds
print(&quot;List comprehension time:&quot;, round(comp_list_speed * 1e6, 2), &quot;microseconds&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12014617754173127678&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;You can see list comprehension takes less time compared to traditional loop. It is faster than the for-loop, but keep in mind that for complex logic for-loop is more favorable than list comprehension. &lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 1;&quot;&gt;In conclusion, we discussed that list comprehension is a great way to generate a concise list &lt;strong&gt;without writing multiple lines of code&lt;/strong&gt;. They are much &lt;strong&gt;faster compared to traditional for-loop&lt;/strong&gt; and also provide better performance. They are easy to understand, efficient, and make the program maintainable. These all added the benefits of &lt;strong&gt;making your code neat and professional&lt;/strong&gt;. It can also be embedded with other built-in functions of Python, making it preferable for Python developers than the traditional one. Although, the concept looks quite complex at first. But once you grasp its syntax, you will never look back. Happy Coding! &lt;/p&gt;
&lt;hr&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt;   
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions&quot; target=&quot;_blank&quot; title=&quot;file&quot;&gt;Using List Comprehension&lt;/a&gt; &lt;/p&gt;
</description>
<category>Lists</category>
<guid isPermaLink="true">https://coderlegion.com/306/advanced-python-concepts-list-comprehensions</guid>
<pubDate>Thu, 30 May 2024 11:29:55 +0000</pubDate>
</item>
</channel>
</rss>