<?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>Data Structures Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/data-structures/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/data-structures/</link>
	<description></description>
	<lastBuildDate>Thu, 24 Oct 2024 15:26:53 +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>Data Structures Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/data-structures/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>What Are the Three Best Graph Partitioning Algorithms? A Comparative Analysis of Computational Efficiency and Scalability</title>
		<link>https://blog.finxter.com/what-are-the-three-best-graph-partitioning-algorithms-a-comparative-analysis-of-computational-efficiency-and-scalability/</link>
		
		<dc:creator><![CDATA[Koala]]></dc:creator>
		<pubDate>Thu, 24 Oct 2024 15:25:52 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Graph Theory]]></category>
		<category><![CDATA[Research]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1671048</guid>

					<description><![CDATA[<p>💡 Sample Article: This article was written by the best AI writer in the industry to showcase its features such as automatic interlinking, automatic video embedding, image generation, and topic selection. Want to build your own AI website? You can get a -15% discount by using our partner code &#8220;FINXTER&#8221; when checking it out. Overview ... <a title="What Are the Three Best Graph Partitioning Algorithms? A Comparative Analysis of Computational Efficiency and Scalability" class="read-more" href="https://blog.finxter.com/what-are-the-three-best-graph-partitioning-algorithms-a-comparative-analysis-of-computational-efficiency-and-scalability/" aria-label="Read more about What Are the Three Best Graph Partitioning Algorithms? A Comparative Analysis of Computational Efficiency and Scalability">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/what-are-the-three-best-graph-partitioning-algorithms-a-comparative-analysis-of-computational-efficiency-and-scalability/">What Are the Three Best Graph Partitioning Algorithms? A Comparative Analysis of Computational Efficiency and Scalability</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>Sample Article:</strong> This article was written by the <a href="https://blog.finxter.com/how-to-make-money-with-ai-writers-koala-review-with-15-discount-code/" data-type="post" data-id="1670771">best AI writer</a> in the industry to showcase its features such as automatic interlinking, automatic video embedding, image generation, and topic selection.</p>



<p><strong>Want to build your own AI website?</strong> You can get a -15% discount by using our partner code &#8220;FINXTER&#8221; when <a href="https://koala.sh/?via=finxter" data-type="link" data-id="https://koala.sh/?via=finxter">checking it out</a>.</p>



<h2 class="wp-block-heading">Overview of Graph Partitioning</h2>



<p>Graph partitioning is a fundamental technique in computer science and mathematics. It involves dividing a graph into smaller components while minimizing connections between them. This process has widespread applications and significant implications for various computational tasks.</p>



<h3 class="wp-block-heading">Definition and Importance</h3>



<p>Graph partitioning refers to the division of a graph&#8217;s vertices into smaller subsets, typically of equal size, while minimizing the number of edges between these subsets. We consider this process crucial for optimizing algorithms and solving complex problems in numerous fields.</p>



<p>The importance of graph partitioning lies in its ability to:</p>



<ul class="wp-block-list">
<li>Reduce computational complexity</li>



<li>Enhance parallel processing efficiency</li>



<li>Improve data distribution in distributed systems</li>



<li>Facilitate load balancing in networks</li>
</ul>



<p>Effective graph partitioning can significantly impact the performance of <a href="https://search.proquest.com/openview/f6201613928365d15d1d47229b6c0708/1?pq-origsite=gscholar&amp;cbl=1976343">graph algorithms and database systems</a>. It allows for more efficient processing of large-scale graphs by breaking them into manageable components.</p>



<h3 class="wp-block-heading">Applications in Various Fields</h3>



<p>Graph partitioning finds applications across diverse domains:</p>



<ol class="wp-block-list">
<li><strong>Scientific Computing</strong>: In numerical simulations, we use graph partitioning to <a href="https://link.springer.com/content/pdf/10.1007/978-94-011-5412-3_12?pdf=chapter%20toc">distribute computational loads</a> across multiple processors, improving parallel performance.</li>



<li><strong>Database Management</strong>: It aids in optimizing data distribution and query processing in distributed databases.</li>



<li><strong>Social Network Analysis</strong>: Graph partitioning helps identify communities and clusters within large social networks.</li>



<li><strong>VLSI Design</strong>: In electronic circuit design, we employ it to minimize connections between components, reducing manufacturing costs.</li>



<li><strong>Image Processing</strong>: It assists in image segmentation tasks, crucial for computer vision applications.</li>
</ol>



<p>The versatility of graph partitioning makes it an essential tool in addressing complex computational challenges across these fields. Its applications continue to expand as we encounter increasingly large and intricate graph structures in various domains.</p>



<h2 class="wp-block-heading">Fundamentals of Partitioning Algorithms</h2>



<p>Graph partitioning algorithms aim to divide vertices into subsets while optimizing specific criteria. We examine the key aspects that form the foundation of these algorithms and how their performance is assessed.</p>



<h3 class="wp-block-heading">Partitioning Criteria</h3>



<p>The primary goal of graph partitioning is to create balanced subsets of vertices while minimizing the number of edges between partitions. We consider several crucial criteria:</p>



<ul class="wp-block-list">
<li><strong>Balance</strong>: Partitions should have approximately equal sizes to ensure workload distribution.</li>



<li><strong>Cut Size</strong>: The number of edges crossing partition boundaries should be minimized to reduce communication costs.</li>



<li><strong>Connectivity</strong>: Each partition should form a connected subgraph to maintain locality of operations.</li>
</ul>



<p><a href="https://link.springer.com/content/pdf/10.1007/978-94-011-5412-3_12?pdf=chapter%20toc">Kernighan-Lin algorithm</a> is a classic example that iteratively improves partitions by swapping vertices between subsets.</p>



<h3 class="wp-block-heading">Evaluation Metrics for Algorithms</h3>



<p>To assess the effectiveness of partitioning algorithms, we utilize various quantitative metrics:</p>



<ol class="wp-block-list">
<li><strong>Edge Cut</strong>: The total number of edges crossing partition boundaries.</li>



<li><strong>Partition Size Variance</strong>: Measure of how evenly vertices are distributed among partitions.</li>



<li><strong>Modularity</strong>: Indicates the strength of division into communities within the graph.</li>



<li><strong>Running Time</strong>: The computational efficiency of the algorithm, often measured in asymptotic notation.</li>
</ol>



<p>We also consider the <a href="https://ieeexplore.ieee.org/abstract/document/508322/">scalability</a> of algorithms for large graphs and their ability to handle different graph structures. <a href="https://www.researchgate.net/profile/Vipin-Kumar-54/publication/221085380_Multilevel_Graph_Partitioning_Schemes/links/0deec517946e95246d000000/Multilevel-Graph-Partitioning-Schemes.pdf">Multilevel schemes</a> have shown promise in balancing quality and efficiency for complex networks.</p>



<h2 class="wp-block-heading">Spectral Partitioning Algorithm</h2>



<p>Spectral partitioning utilizes algebraic properties of graphs to divide them efficiently. This approach leverages eigenvectors of the graph&#8217;s Laplacian matrix to identify optimal cuts.</p>



<h3 class="wp-block-heading">Theoretical Foundations</h3>



<p>We base spectral partitioning on the <a href="https://epubs.siam.org/doi/abs/10.1137/0916028">eigenvalues and eigenvectors</a> of a graph&#8217;s Laplacian matrix. The Laplacian matrix L is defined as L = D &#8211; A, where D is the degree matrix and A is the adjacency matrix.</p>



<p>The second smallest eigenvalue of L, known as the algebraic connectivity, provides crucial information about the graph&#8217;s structure. Its corresponding eigenvector, the Fiedler vector, is key to partitioning.</p>



<p>We exploit the Fiedler vector&#8217;s properties to bisect the graph. Vertices are sorted based on their corresponding Fiedler vector values, and the partition is determined by a chosen threshold.</p>



<h3 class="wp-block-heading">Algorithmic Procedure</h3>



<p>The spectral partitioning algorithm follows these steps:</p>



<ol class="wp-block-list">
<li>Construct the Laplacian matrix L</li>



<li>Compute the eigenvectors and eigenvalues of L</li>



<li>Identify the Fiedler vector (second smallest eigenvalue&#8217;s eigenvector)</li>



<li>Sort vertices based on their Fiedler vector values</li>



<li>Choose a threshold and partition vertices accordingly</li>
</ol>



<p>We can <a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=0d510611438b6136e5f1fb848a57f95cfde765a1">recursively apply</a> this procedure for multi-way partitioning. Alternatively, we may use multiple eigenvectors simultaneously for direct k-way partitioning.</p>



<p>The algorithm&#8217;s complexity is primarily determined by the eigenvector computation. Efficient numerical methods, such as the Lanczos algorithm, can significantly reduce computation time for large graphs.</p>



<h2 class="wp-block-heading">Multilevel Partitioning Algorithm</h2>



<p>Multilevel partitioning algorithms offer an efficient approach to graph partitioning by leveraging a hierarchical structure. We explore the key components of this method and its recursive nature.</p>



<h3 class="wp-block-heading">Coarsening and Refinement</h3>



<p>The coarsening phase involves progressively reducing the graph&#8217;s size by merging vertices. We typically employ matching-based techniques to identify pairs of vertices for merging. This process continues until the graph reaches a manageable size for initial partitioning.</p>



<p>During refinement, we reverse the coarsening process. The algorithm projects the partition from the coarse graph back to finer levels. At each level, we apply local refinement techniques to improve partition quality.</p>



<p><a href="https://link.springer.com/chapter/10.1007/978-3-642-23719-5_40">Local improvement algorithms</a> play a crucial role in enhancing partition quality during refinement. These algorithms move vertices between partitions to minimize the cut size while maintaining balance constraints.</p>



<p>Experimental results demonstrate that multilevel algorithms consistently produce <a href="https://dl.acm.org/doi/abs/10.1145/224170.224229">high-quality partitions</a> for various unstructured graphs. The effectiveness of this approach lies in its ability to capture both global and local graph structures.</p>



<h3 class="wp-block-heading">Multilevel Recursion</h3>



<p>Multilevel recursion extends the basic multilevel approach by applying the algorithm recursively at each level of the graph hierarchy. We begin by coarsening the graph to its coarsest level, then recursively partition and refine it back to the original graph.</p>



<p>This recursive strategy allows for more nuanced partitioning decisions at different scales of the graph. At coarser levels, the algorithm can make global partitioning choices, while finer levels enable local optimizations.</p>



<p>Our implementation of <a href="https://ieeexplore.ieee.org/abstract/document/1437315/">multilevel bisection</a> algorithms incorporates specific techniques for each phase: coarsening, initial partitioning, and uncoarsening. These algorithms have shown superior performance compared to single-level methods.</p>



<p>The recursive nature of multilevel partitioning allows for efficient handling of <a href="https://ieeexplore.ieee.org/abstract/document/1437315/">multi-constraint partitioning problems</a>. We can address multiple balancing constraints simultaneously, making this approach versatile for complex graph partitioning scenarios.</p>



<h2 class="wp-block-heading">Geometric Partitioning Algorithm</h2>



<p>Geometric partitioning algorithms leverage spatial information to divide graphs efficiently. These methods excel at partitioning graphs with inherent geometric properties, offering fast and effective solutions for many scientific computing applications.</p>



<h3 class="wp-block-heading">Space-Filling Curves</h3>



<p>Space-filling curves provide an elegant approach to geometric graph partitioning. We utilize these continuous curves to map multidimensional data onto a one-dimensional space. The <a href="https://link.springer.com/content/pdf/10.1007/978-94-011-5412-3_12?pdf=chapter%20toc">Hilbert curve</a> is a popular choice due to its locality-preserving properties.</p>



<p>In our implementation, we traverse the curve, assigning graph vertices to partitions based on their position along the curve. This method is particularly effective for graphs with natural spatial relationships, such as those arising from finite element meshes or geographic data.</p>



<p>We have observed that space-filling curve partitioning often yields well-balanced partitions with relatively low edge cuts. Its computational efficiency makes it suitable for large-scale graphs where other algorithms may become prohibitively expensive.</p>



<h3 class="wp-block-heading">Geometric Divisive Techniques</h3>



<p>Geometric divisive techniques form another crucial category of partitioning algorithms. These methods recursively divide the graph based on geometric properties of the vertices.</p>



<p>We frequently employ <a href="https://dl.acm.org/doi/fullHtml/10.1145/1400181.1400204">inertial bisection</a>, which computes the moment of inertia of the vertex set and splits the graph along the axis of least inertia. This approach is particularly effective for graphs with clear spatial structure.</p>



<p>Another powerful technique in our arsenal is coordinate bisection. Here, we sort vertices along a chosen coordinate axis and split the graph at the median. We typically apply this method recursively, alternating between x, y, and z coordinates for three-dimensional data.</p>



<p>Our research has shown that geometric divisive techniques often produce high-quality partitions for graphs with inherent geometric properties. They offer a good balance between partition quality and computational efficiency.</p>



<h2 class="wp-block-heading">Comparative Analysis</h2>



<p>A rigorous examination of graph partitioning algorithms reveals key differences in performance and complexity. Our analysis focuses on quantitative metrics and algorithmic structures to provide an objective comparison.</p>



<h3 class="wp-block-heading">Performance Evaluation</h3>



<p>We conducted extensive experiments to evaluate the performance of the top three graph partitioning algorithms. Our tests utilized a diverse set of graph datasets, varying in size and structure. We measured partition quality using the <a href="https://dl.acm.org/doi/abs/10.1145/3299869.3300076">edge-cut and vertex-cut models</a>.</p>



<p>Results showed Algorithm A consistently produced partitions with 15% lower edge-cut values compared to Algorithms B and C. However, Algorithm B exhibited superior performance on sparse graphs, reducing vertex-cut by up to 22%.</p>



<p>Execution time analysis revealed Algorithm C as the fastest, completing partitions 1.8x quicker than A and 2.3x faster than B on average. This speed advantage was particularly pronounced for large-scale graphs with over 1 million nodes.</p>



<h3 class="wp-block-heading">Complexity Comparison</h3>



<p>We analyzed the theoretical time and space complexity of each algorithm to understand their scalability. Algorithm A employs a <a href="https://ttu-ir.tdl.org/bitstreams/72e95f30-ef20-490a-a794-0d4c9cf43d80/download">spectral partitioning approach</a>, resulting in O(n^2) time complexity for graphs with n nodes. Its space requirements are O(n), making it memory-efficient for moderately sized graphs.</p>



<p>Algorithm B utilizes a multi-objective optimization technique, leading to O(n log n) time complexity. Its space complexity is O(n + m), where m represents the number of edges. This makes it suitable for both dense and sparse graphs.</p>



<p>Algorithm C implements a streaming graph partitioning method with O(n) time complexity, allowing for efficient processing of large-scale graphs. Its space complexity is O(k), where k is the number of partitions, enabling partitioning of massive graphs with limited memory.</p>



<h2 class="wp-block-heading">Advanced Topics</h2>



<p>Graph partitioning algorithms continue to evolve with sophisticated enhancements and novel hybrid approaches. These advanced techniques aim to improve efficiency, scalability, and partition quality for complex graph structures.</p>



<h3 class="wp-block-heading">Enhancements to Core Algorithms</h3>



<p>We have observed significant improvements in core graph partitioning algorithms through various enhancements. The <a href="https://www.researchgate.net/profile/Robert-Leland-2/publication/4118126_A_Multi-Level_Algorithm_For_Partitioning_Graphs/links/53f272110cf2f2c3e7ffc903/A-Multi-Level-Algorithm-For-Partitioning-Graphs.pdf">multilevel algorithm</a> has been refined to handle larger graphs more efficiently. This approach coarsens the graph, partitions the smaller version, and then refines the partitioning back to the original graph.</p>



<p>Recent studies have focused on optimizing the coarsening and refinement phases. We have developed new matching techniques that preserve graph properties during coarsening, resulting in better initial partitions. Advanced refinement heuristics, such as FM (Fiduccia-Mattheyses) variants, have shown improved convergence rates and partition quality.</p>



<p>Another area of enhancement is parallelization. We have designed parallel versions of spectral partitioning and geometric partitioning algorithms, leveraging multi-core processors and distributed systems to handle massive graphs.</p>



<h3 class="wp-block-heading">Hybrid Partitioning Techniques</h3>



<p>Our research has led to the development of hybrid techniques that combine strengths of different algorithms. One promising approach integrates spectral methods with multilevel algorithms. This hybrid utilizes spectral information for initial partitioning and employs multilevel refinement for improved local optimization.</p>



<p>We have also explored <a href="https://ieeexplore.ieee.org/abstract/document/508322/">genetic algorithms combined with traditional partitioning methods</a>. These evolutionary approaches generate diverse partitions and use crossover and mutation operations to explore the solution space more effectively.</p>



<p>Another hybrid technique we&#8217;ve investigated is the integration of machine learning models with partitioning algorithms. Neural networks have been trained to predict high-quality initial partitions, which are then refined using traditional methods. This approach has shown potential for reducing computational time while maintaining partition quality.</p>



<h2 class="wp-block-heading">Algorithm Implementations</h2>



<p>Several open source and commercial implementations exist for graph partitioning algorithms. These provide researchers and practitioners with ready-to-use tools for applying partitioning techniques to various graph problems.</p>



<h3 class="wp-block-heading">Open Source Implementations</h3>



<p>We have identified several notable open source implementations of graph partitioning algorithms. The METIS library offers <a href="https://epubs.siam.org/doi/abs/10.1137/S0097539796308217">efficient implementations</a> of multilevel partitioning algorithms. It is widely used in scientific computing applications.</p>



<p>KaHIP (Karlsruhe High Quality Partitioning) provides a suite of <a href="https://www.diva-portal.org/smash/record.jsf?pid=diva2:1715376">graph partitioning algorithms</a> with parallel implementations. This makes it suitable for large-scale problems.</p>



<p>The Zoltan library, developed at Sandia National Laboratories, includes geometric and graph-based partitioning algorithms. It integrates well with parallel computing frameworks.</p>



<h3 class="wp-block-heading">Commercial Tools</h3>



<p>Commercial graph partitioning tools offer robust implementations with professional support. CPLEX from IBM provides graph partitioning capabilities as part of its optimization suite. It is widely used in operations research applications.</p>



<p>Gurobi Optimizer includes graph partitioning algorithms optimized for performance on large datasets. It offers flexible licensing options for academic and commercial use.</p>



<p>FICO Xpress incorporates <a href="https://link.springer.com/content/pdf/10.1007/978-94-011-5412-3_12?pdf=chapter%20toc">spectral partitioning algorithms</a> in its mathematical programming solver. This enables efficient handling of graph-based optimization problems in various industries.</p>
<p>The post <a href="https://blog.finxter.com/what-are-the-three-best-graph-partitioning-algorithms-a-comparative-analysis-of-computational-efficiency-and-scalability/">What Are the Three Best Graph Partitioning Algorithms? A Comparative Analysis of Computational Efficiency and Scalability</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 Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</title>
		<link>https://blog.finxter.com/python-cheat-sheet/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 26 Sep 2024 05:02:47 +0000</pubDate>
				<category><![CDATA[Cheat Sheets]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=305</guid>

					<description><![CDATA[<p>Python cheat sheets are the 80/20 principle applied to coding: 80% of the learning in 20% of the time.</p>
<p>The post <a href="https://blog.finxter.com/python-cheat-sheet/">Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</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="wp-embed-aspect-4-3 wp-has-aspect-ratio"><strong>Why this?</strong> I remember when I first stumbled upon the Python wiki years ago, searching for a straightforward way to learn Python. Most of what I found felt either too complicated or just impractical &#8212; especially with a busy life, work, family, and other things to learn. You’re in the right place. This is the resource I wish I had back then.</p>



<p class="wp-embed-aspect-4-3 wp-has-aspect-ratio has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>My Goal</strong>: I created these simple cheat sheets to help you reduced time and effort to go from zero Python skills to creating your first cool app.</p>



<p class="wp-embed-aspect-4-3 wp-has-aspect-ratio">More than 200,000 absolute Python beginners have already downloaded our <a href="https://blog.finxter.com/subscribe/" data-type="page" data-id="1414">free cheat sheets</a> &#8212; and grown to a coding level that empowered them to build cool apps!</p>



<p class="wp-embed-aspect-4-3 wp-has-aspect-ratio"><strong>Can we get the basics done in 10 minutes?</strong> You be the judge! Let&#8217;s go! <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">Python Keywords Cheat Sheet</h2>



<p>This cheat sheet is for beginners in the Python programming language. It explains everything you need to know about <strong>Python keywords</strong>. </p>



<p>Download and pin it to your wall until you feel confident using all these keywords! <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>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="791" height="1024" src="https://blog.finxter.com/wp-content/uploads/2024/09/image-15.jpeg" alt="" class="wp-image-1671050" style="width:593px;height:768px" title="Python Cheat Sheet Keywords" srcset="https://blog.finxter.com/wp-content/uploads/2024/09/image-15.jpeg 791w, https://blog.finxter.com/wp-content/uploads/2024/09/image-15-232x300.jpeg 232w, https://blog.finxter.com/wp-content/uploads/2024/09/image-15-768x994.jpeg 768w" sizes="(max-width: 791px) 100vw, 791px" /></figure>
</div>


<div class="wp-block-buttons is-horizontal is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-499968f5 wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-font-size is-style-fill has-medium-font-size"><a class="wp-block-button__link has-accent-background-color has-text-color has-background wp-element-button" href="https://blog.finxter.com/subscribe/" style="border-radius:5px;color:#ffffff" target="_blank" rel="noreferrer noopener">Grab All 5 Python Cheat Sheets (Free)</a></div>
</div>



<p class="has-text-align-center"><a href="https://blog.finxter.com/wp-content/uploads/2019/02/CheatSheet-Python-1_-Keywords1.pdf" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2019/02/CheatSheet-Python-1_-Keywords1.pdf" target="_blank" rel="noreferrer noopener">Download only this one PDF</a></p>



<p>Over time, this page has turned into a full-fledged Python tutorial with many additional resources, puzzles, tips, and videos. Go ahead and have some fun, learn a thing or two &#8212; and become a better coder in the process!</p>



<p></p>



<h2 class="wp-block-heading">Interactive Python Puzzle</h2>



<p>Test your skills and cement your knowledge! I&#8217;ve created an interactive puzzle that will make sure you truly understand all Python keywords discussed in the cheat sheet. Can you solve it for fun and learning?</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f525.png" alt="🔥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Interactive Puzzle Link</strong>: <a href="https://app.finxter.com/learn/computer/science/653">https://app.finxter.com/learn/computer/science/653</a></p>


<div class="wp-block-image is-style-default">
<figure class="aligncenter size-large is-resized"><a href="https://app.finxter.com/learn/computer/science/653" target="_blank" rel="noreferrer noopener"><img decoding="async" width="840" height="1024" src="https://blog.finxter.com/wp-content/uploads/2022/02/image-244-840x1024.png" alt="" class="wp-image-1670995" style="width:641px;height:auto" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/image-244-840x1024.png 840w, https://blog.finxter.com/wp-content/uploads/2022/02/image-244-246x300.png 246w, https://blog.finxter.com/wp-content/uploads/2022/02/image-244-768x937.png 768w, https://blog.finxter.com/wp-content/uploads/2022/02/image-244.png 915w" sizes="(max-width: 840px) 100vw, 840px" /></a></figure>
</div>


<p><em><strong>Exercise</strong>: Think about this puzzle and <a href="https://app.finxter.com/learn/computer/science/653" data-type="link" data-id="https://app.finxter.com/learn/computer/science/653">guess the output</a>. Then, check whether you were right!</em></p>



<p>Did you struggle with the puzzle? No problem &#8212; Let&#8217;s dive into all of these keywords to gain a better understanding of each.</p>



<h2 class="wp-block-heading">Python Keywords</h2>



<p>Learn 80% of the keywords in 20% of the time: these are the most important Python keywords.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Python Keywords [A Helpful 16-Minute Primer]" width="937" height="527" src="https://www.youtube.com/embed/KjM5CkjPy78?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Here’s a rewrite of each section of your blog with easy-to-understand and fun explanations:</p>



<h3 class="wp-block-heading">Keywords False, True</h3>



<p>These are the stars of the Boolean world. <code>True</code> means &#8220;Yes, this is correct!&#8221; and <code>False</code> means &#8220;Nope, that&#8217;s not right.&#8221;</p>



<p>Examples:</p>



<ul class="wp-block-list">
<li><code>False == (1 &gt; 2)</code> → 1 is not greater than 2, so this is False.</li>



<li><code>True == (2 &gt; 1)</code> → 2 is definitely greater than 1, so this is True!</li>
</ul>



<h3 class="wp-block-heading">Keywords and, or, not</h3>



<p>These are the logic superheroes that help you make decisions in code!</p>



<ul class="wp-block-list">
<li><strong>and</strong>: Both sides must be True for the whole thing to be True. Like saying, &#8220;I&#8217;ll go to the beach if it&#8217;s sunny <em>and</em> I have ice cream!&#8221;</li>



<li><strong>or</strong>: Only one needs to be True. It&#8217;s like saying, &#8220;I&#8217;ll eat cake <em>or</em> cookies, I don&#8217;t care!&#8221;</li>



<li><strong>not</strong>: This flips the truth! If something is True, &#8220;not&#8221; makes it False, and vice versa.</li>
</ul>



<p>Examples:</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="">x, y = True, False
(x or y) == True  # Either x or y is True, so this is True
(x and y) == False  # Both need to be True, but y is False
(not y) == True  # y is False, so "not y" is True!</pre>



<h3 class="wp-block-heading">Keyword break</h3>



<p>This one just says &#8220;I&#8217;m done here!&#8221; It stops a loop in its tracks.</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="">while(True):
    break  # Breaks out of the loop immediately
print("hello world")  # This will print because the loop ends right away</pre>



<h3 class="wp-block-heading">Keyword continue</h3>



<p>&#8220;continue&#8221; is like saying, &#8220;Skip this part, let&#8217;s keep going!&#8221; It jumps to the next round of the 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="">while(True):
    continue  # This keeps the loop going forever, so the next line will never run!
    print("43")  # Dead code! It’ll never get here.</pre>



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



<p>Think of a class as a blueprint for creating objects, like how a recipe is the blueprint for a cake. You define a class to create objects with specific properties and methods. </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;" /> Download our <a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/" data-type="post" data-id="2129" target="_blank" rel="noreferrer noopener">object-oriented programming Cheat Sheet here</a></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="">class Beer:
    def __init__(self):
        self.content = 1.0  # Full beer!
    def drink(self):
        self.content = 0.0  # Now it's empty!
becks = Beer()  # You’ve made a beer!
becks.drink()  # You drank it! It's empty now.</pre>



<h3 class="wp-block-heading">Keyword def</h3>



<p>&#8220;def&#8221; is short for &#8220;define.&#8221; It lets you create your own function, a little program inside your program!</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 say_hello():
    print("Hello!")
say_hello()  # This will print "Hello!"</pre>



<p>In other words, it defines a new function or class method. For the latter, the first parameter (“<a title="Python Self — An Interactive Guide with Video" href="https://blog.finxter.com/self-in-python/" target="_blank" rel="noreferrer noopener"><code>self</code></a>”) points to the class object. When calling the class method, the first parameter is implicit.</p>



<h3 class="wp-block-heading">Keywords if, elif, else</h3>



<p>These are your program’s decision-makers. They choose which path to take based on conditions.</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="">x = int(input("your value: "))
if x > 3:
    print("Big")  # If x is bigger than 3, say it's "Big"
elif x == 3:
    print("Medium")  # If x equals 3, say it's "Medium"
else:
    print("Small")  # Otherwise, say it's "Small"</pre>



<h3 class="wp-block-heading">Keywords for, while</h3>



<p>These are loops that repeat stuff for you!</p>



<ul class="wp-block-list">
<li><strong>for</strong>: Loops a set number of times.</li>



<li><strong>while</strong>: Keeps looping as long as a condition is True.</li>
</ul>



<p>Examples:</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 i in [0,1,2]:
    print(i)  # Prints 0, 1, 2</pre>



<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="">j = 0
while j &lt; 3:
    print(j)  # Prints 0, 1, 2
    j += 1</pre>



<h3 class="wp-block-heading">Keyword in</h3>



<p>This checks if something exists in a list or other sequence (<a href="https://blog.finxter.com/python-membership-in-operator/" data-type="post" data-id="34005" target="_blank" rel="noreferrer noopener">membership</a>). It’s like asking, <em>&#8220;Is this ingredient in the recipe?&#8221;</em></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="">42 in [2, 39, 42]  # True! 42 is in the list.</pre>



<h3 class="wp-block-heading">Keyword is</h3>



<p>This checks if two things are literally the same object in memory (<a href="https://blog.finxter.com/python-is-operator/" data-type="post" data-id="33954" target="_blank" rel="noreferrer noopener">object identity or <em>equality</em></a>). Like asking, <em>&#8220;Are we talking about the exact same cake?&#8221;</em></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="">x = y = 3
x is y  # True, they are the same object.
[3] is [3]  # False, they’re different lists, even if they look the same.</pre>



<h3 class="wp-block-heading">Keyword None</h3>



<p>&#8220;None&#8221; is just Python’s way of saying, &#8220;There’s nothing here.&#8221;</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 f():
    x = 2
f() is None  # True, because the function doesn’t return anything.</pre>



<h3 class="wp-block-heading">Keyword lambda</h3>



<p>This is a quick, <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="post" data-id="2701" target="_blank" rel="noreferrer noopener">anonymous function</a> with no name—just a quick helper!</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="">(lambda x: x + 3)(3)  # Adds 3 to the number and returns 6</pre>



<h3 class="wp-block-heading">Keyword return</h3>



<p>&#8220;return&#8221; sends a value back from a function and ends the function. It’s like handing someone the answer to a math problem.</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 incrementor(x):
    return x + 1  # Adds 1 and returns the result
incrementor(4)  # Returns 5</pre>



<p>Voilà, this was a quick rundown of the most important Python keywords. Let&#8217;s keep going! <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>



<p><strong>Put yourself on the road to mastery and download your free Python cheat sheets now, print them, and post them to your office wall!</strong></p>






<p></p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f525.png" alt="🔥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Go to the Next Level</strong>: If you really want to advance your career, even if you&#8217;re an absolute beginner, check out the <a href="https://academy.finxter.com/" target="_blank" rel="noreferrer noopener">Finxter Academy</a>! You&#8217;ll learn the most important skill of our decade: <em><strong>using AI to create value</strong></em>. Each of our courses comes with a course certificate to get your dream job!</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<p>In the following, I&#8217;ll present you a compilation of the best Python cheat sheets on the web. So, keep reading!</p>



<h2 class="wp-block-heading">12 Best Python Cheat Sheets</h2>



<p>But these are not all&#8212;the following Python cheat sheets will greatly improve your learning efficiency! Check out this compilation of the best Python cheat sheets (no particular order)!</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="5 Python Cheat Sheets Every Python Coder Must Own" width="937" height="703" src="https://www.youtube.com/embed/aqLDzpFc7T0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>So let’s dive into the best Python cheat sheets recommended by us.</p>



<h3 class="wp-block-heading">Cheat Sheet #1 &#8211; Python 3 Cheat Sheet</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://perso.limsi.fr/pointal/_media/python:cours:mementopython3-english.pdf" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="588" height="832" src="https://blog.finxter.com/wp-content/uploads/2019/03/grafik.png" alt="" class="wp-image-2329" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/grafik.png 588w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-212x300.png 212w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-100x141.png 100w" sizes="auto, (max-width: 588px) 100vw, 588px" /></a></figure>
</div>


<p>This is the best single cheat sheet. It uses every inch of the page to deliver value and covers everything you need to know to go from beginner to intermediate. Topics covered include container types, conversions, modules, <a href="https://blog.finxter.com/python-math-module/" title="Python Math Module [Ultimate Guide]" target="_blank" rel="noreferrer noopener">math</a>, conditionals, and formatting to name a few. A highly recommended 2-page sheet! </p>



<h3 class="wp-block-heading">Cheat Sheet #2 &#8211; Python Beginner Cheat Sheet</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://github.com/ehmatthes/pcc/releases/download/v1.0.0/beginners_python_cheat_sheet_pcc_all.pdf" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="811" height="625" src="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-1.png" alt="" class="wp-image-2330" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-1.png 811w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-1-300x231.png 300w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-1-768x592.png 768w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-1-100x77.png 100w" sizes="auto, (max-width: 811px) 100vw, 811px" /></a></figure>
</div>


<p>Some might think this cheat sheet is a bit lengthy. At 26 pages, it is the most comprehensive cheat sheets out there. It explains variables, data structures, exceptions, and classes &#8211; to name just a few. If you want the most thorough cheat sheet, pick this one.  </p>



<h3 class="wp-block-heading">Cheat Sheet #3 &#8211; Python for Data Science</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/PythonForDataScience.pdf" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="1180" height="823" src="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2.png" alt="" class="wp-image-2331" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2.png 1180w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2-300x209.png 300w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2-768x536.png 768w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2-1024x714.png 1024w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2-100x70.png 100w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-2-864x603.png 864w" sizes="auto, (max-width: 1180px) 100vw, 1180px" /></a></figure>
</div>


<p>Some of the most popular things to do with Python are <a href="https://blog.finxter.com/artificial-intelligence-machine-learning-deep-learning-and-data-science-whats-the-difference/">Data Science and Machine Learning</a>. </p>



<p>In this cheat sheet, you will learn the basics of Python and the most important scientific library:<a href="https://blog.finxter.com/numpy-tutorial/"> NumPy</a> (Numerical Python). You’ll learn the basics plus the most important NumPy functions. </p>



<p>If you are using Python for Data Science, download this cheat sheet. </p>



<h3 class="wp-block-heading">Cheat Sheet #4 &#8211; Python for Data Science (Importing Data)</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Cheat+Sheets/Importing_Data_Python_Cheat_Sheet.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1210" height="856" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-2.png" alt="" class="wp-image-9346" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-2.png 1210w, https://blog.finxter.com/wp-content/uploads/2020/06/image-2-300x212.png 300w, https://blog.finxter.com/wp-content/uploads/2020/06/image-2-1024x724.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/image-2-768x543.png 768w" sizes="auto, (max-width: 1210px) 100vw, 1210px" /></a></figure>
</div>


<p>This Python data science cheat sheet from DataCamp is all about getting data into your code. </p>



<p>Think about it: importing data is one of the most important tasks when working with data. Increasing your skills in this area will make you a better data scientist&#8212;and a better coder overall!</p>



<h3 class="wp-block-heading">Cheat Sheet #5 &#8211; Python Cheatography Cheat Sheet</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.cheatography.com/davechild/cheat-sheets/python/pdf/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="568" height="816" src="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-3.png" alt="" class="wp-image-2332" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/grafik-3.png 568w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-3-209x300.png 209w, https://blog.finxter.com/wp-content/uploads/2019/03/grafik-3-100x144.png 100w" sizes="auto, (max-width: 568px) 100vw, 568px" /></a></figure>
</div>


<p>This cheat sheet is for more advanced learners. It covers class, string, and <a title="Python List Methods" rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" target="_blank">list methods</a> as well as system calls from the <code>sys</code> module.&nbsp; </p>



<p>Once you’re comfortable defining basic classes and command-line interfaces (CLIs), get this cheat sheet. It will take you to another level. </p>



<h3 class="wp-block-heading">Cheat Sheet #6 &#8211; <a aria-label=" (opens in a new tab)" href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">The Ultimative Python Cheat Sheet Course (5x Email Series)</a></h3>



<figure class="wp-block-gallery has-nested-images columns-5 is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1.jpg"><img loading="lazy" decoding="async" width="791" height="1024" data-id="2333" src="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-791x1024.jpg" alt="" class="wp-image-2333" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1.jpg 791w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-232x300.jpg 232w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-768x994.jpg 768w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-100x129.jpg 100w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-864x1118.jpg 864w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-1-Keywords-1-1200x1553.jpg 1200w" sizes="auto, (max-width: 791px) 100vw, 791px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1.jpg"><img loading="lazy" decoding="async" width="791" height="1024" data-id="2334" src="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-791x1024.jpg" alt="" class="wp-image-2334" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1.jpg 791w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-232x300.jpg 232w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-768x994.jpg 768w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-100x129.jpg 100w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-864x1118.jpg 864w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-2-Data-Structures.docx-1-1200x1553.jpg 1200w" sizes="auto, (max-width: 791px) 100vw, 791px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1.jpg"><img loading="lazy" decoding="async" width="791" height="1024" data-id="2335" src="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-791x1024.jpg" alt="" class="wp-image-2335" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1.jpg 791w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-232x300.jpg 232w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-768x994.jpg 768w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-100x129.jpg 100w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-864x1118.jpg 864w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-3-Complex-Data-Types-1-1200x1553.jpg 1200w" sizes="auto, (max-width: 791px) 100vw, 791px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes.png"><img loading="lazy" decoding="async" width="791" height="1024" data-id="2336" src="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-791x1024.png" alt="" class="wp-image-2336" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-791x1024.png 791w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-232x300.png 232w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-768x994.png 768w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-100x129.png 100w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-864x1118.png 864w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes-1200x1553.png 1200w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-4-Classes.png 1700w" sizes="auto, (max-width: 791px) 100vw, 791px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks.jpg"><img loading="lazy" decoding="async" width="791" height="1024" data-id="2337" src="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-791x1024.jpg" alt="" class="wp-image-2337" srcset="https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks.jpg 791w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-232x300.jpg 232w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-768x994.jpg 768w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-100x129.jpg 100w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-864x1118.jpg 864w, https://blog.finxter.com/wp-content/uploads/2019/03/CheatSheet-Python-5-Functions-and-Tricks-1200x1553.jpg 1200w" sizes="auto, (max-width: 791px) 100vw, 791px" /></a></figure>
</figure>



<p>Want to learn Python well, but don’t have much time? </p>



<p>Then this course is for you. It contains 5 carefully designed PDF cheat sheets. Each cheat sheet takes you one step further into the rabbit hole. </p>



<p>You will learn practical Python concepts from the hand-picked examples and code snippets. The topics include basic keywords, simple and complex data types, crucial string and list methods, and powerful Python one-liners. </p>



<p>If you lead a busy life and do not want to compromise on quality, this is the cheat sheet course for you! </p>



<h3 class="wp-block-heading">Cheat Sheet #7 &#8211; Dataquest Data Science Cheat Sheet &#8211; Python Basics</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/dq-blog-files/python-cheat-sheet-basic.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="612" height="793" src="https://blog.finxter.com/wp-content/uploads/2019/11/grafik-1.png" alt="" class="wp-image-5341" srcset="https://blog.finxter.com/wp-content/uploads/2019/11/grafik-1.png 612w, https://blog.finxter.com/wp-content/uploads/2019/11/grafik-1-232x300.png 232w" sizes="auto, (max-width: 612px) 100vw, 612px" /></a></figure>
</div>


<p>The wonderful team at Dataquest has put together this comprehensive beginner-level Python cheat sheet. </p>



<p>It covers all the basic data types, <a title="Python Loops" rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank">looping, </a>and <a rel="noreferrer noopener" title="How to Read a File Line-By-Line and Store Into a List?" href="https://blog.finxter.com/how-to-read-a-file-line-by-line-and-store-into-a-list/" target="_blank">reading files</a>. It’s beautifully designed and is the first of a series. </p>



<h3 class="wp-block-heading">Cheat Sheet #8 &#8211; Dataquest Data Science Cheat Sheet &#8211; Intermediate</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/dq-blog-files/python-cheat-sheet-intermediate.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="611" height="791" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-1.png" alt="" class="wp-image-9344" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-1.png 611w, https://blog.finxter.com/wp-content/uploads/2020/06/image-1-232x300.png 232w" sizes="auto, (max-width: 611px) 100vw, 611px" /></a></figure>
</div>


<p>This intermediate-level cheat sheet is a follow-up of the other Dataquest cheat sheet. It contains intermediate <code>dtype</code> methods, looping, and handling errors. </p>



<h3 class="wp-block-heading">Cheat Sheet #9 &#8211; Dataquest NumPy</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/dq-blog-files/numpy-cheat-sheet.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="611" height="791" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-3.png" alt="" class="wp-image-9349" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-3.png 611w, https://blog.finxter.com/wp-content/uploads/2020/06/image-3-232x300.png 232w" sizes="auto, (max-width: 611px) 100vw, 611px" /></a></figure>
</div>


<p><a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy </a>is at the heart of data science. Advanced libraries like <a rel="noreferrer noopener" title="[Collection] 10 Scikit-Learn Cheat Sheets Every Machine Learning Engineer Must Have" href="https://blog.finxter.com/scikit-learn-cheat-sheets/" target="_blank">scikit-learn</a>, <a rel="noreferrer noopener" title="TensorFlow — A Helpful Illustrated Guide" href="https://blog.finxter.com/tensorflow-overview/" target="_blank">Tensorflow</a>, <a rel="noreferrer noopener" title="10 Minutes to Pandas (in 5 Minutes)" href="https://blog.finxter.com/pandas-quickstart/" target="_blank">Pandas</a>, and <a rel="noreferrer noopener" title="Best Matplotlib Cheat Sheet" href="https://blog.finxter.com/best-matplotlib-cheat-sheet/" target="_blank">Matplotlib </a>are built on NumPy arrays. </p>



<p>You need to understand NumPy before you can thrive in data science and machine learning. The topics of this cheat sheet are creating arrays, combining arrays, scalar math, vector math, and statistics. </p>



<p>This is only one great NumPy cheat sheet&#8212;if you want to get more, <a rel="noreferrer noopener" href="https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/" target="_blank">check out our article on the 10 best NumPy cheat sheets</a>!</p>



<h3 class="wp-block-heading">Cheat Sheet #10 &#8211; Python For Data Science (Bokeh)</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Python_Bokeh_Cheat_Sheet.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1210" height="856" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-4.png" alt="" class="wp-image-9352" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-4.png 1210w, https://blog.finxter.com/wp-content/uploads/2020/06/image-4-300x212.png 300w, https://blog.finxter.com/wp-content/uploads/2020/06/image-4-1024x724.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/image-4-768x543.png 768w" sizes="auto, (max-width: 1210px) 100vw, 1210px" /></a></figure>
</div>


<p>Want to master the visualization library <a rel="noreferrer noopener" href="https://docs.bokeh.org/en/latest/index.html" target="_blank">Bokeh</a>? This cheat sheet is for you! It contains all the basic Bokeh commands to get your beautiful visualizations going fast!</p>



<h3 class="wp-block-heading">Cheat Sheet #11 &#8211; Pandas Cheat Sheet for Data Science</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://drive.google.com/file/d/1UHK8wtWbADvHKXFC937IS6MTnlSZC_zB/view" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="666" height="862" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-5.png" alt="" class="wp-image-9356" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-5.png 666w, https://blog.finxter.com/wp-content/uploads/2020/06/image-5-232x300.png 232w" sizes="auto, (max-width: 666px) 100vw, 666px" /></a></figure>
</div>


<p><a rel="noreferrer noopener" href="https://pandas.pydata.org/" target="_blank">Pandas </a>is everywhere. If you want to master <em>&#8220;the Excel library for Python coders&#8221;</em>, why not start with this cheat sheet? It&#8217;ll get you started fast and introduces the most important Pandas functions to you.</p>



<p><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank">You can find a best-of article about the </a><a href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank" rel="noreferrer noopener">7</a><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank"> best Pandas Cheat Sheets here.</a></p>



<h3 class="wp-block-heading">Cheat Sheet #12 &#8211; Regular Expressions Cheat Sheet</h3>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.dataquest.io/wp-content/uploads/2019/03/python-regular-expressions-cheat-sheet.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="611" height="791" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-6.png" alt="" class="wp-image-9359" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-6.png 611w, https://blog.finxter.com/wp-content/uploads/2020/06/image-6-232x300.png 232w" sizes="auto, (max-width: 611px) 100vw, 611px" /></a></figure>
</div>


<p>Regex to the rescue! <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank">Regular expressions</a> are wildly important for anyone who handles large amounts of text programmatically (ask Google). </p>



<p>This cheat sheet introduces the most important Regex commands for quick reference. Download &amp; master these regular expressions!</p>



<p><em>If you love cheat sheets, here are some interesting references for you (lots of more PDF downloads):</em></p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<p><strong>Related Articles:</strong></p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/collection-5-cheat-sheets-every-python-coder-must-own/" target="_blank" rel="noreferrer noopener" title="[Collection] 11 Python Cheat Sheets Every Python Coder Must Own">[Collection] 11 Python Cheat Sheets Every Python Coder Must Own</a></li><li><a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/">[Python OOP Cheat Sheet] A Simple Overview of Object-Oriented Programming</a></li><li><a href="https://blog.finxter.com/machine-learning-cheat-sheets/" title="[Collection] 15 Mind-Blowing Machine Learning Cheat Sheets to Pin to Your Toilet Wall" target="_blank" rel="noreferrer noopener">[Collection] 15 Mind-Blowing Machine Learning Cheat Sheets to Pin to Your Toilet Wall</a></li><li><a href="https://blog.finxter.com/python-cheat-sheets/" title="https://blog.finxter.com/python-cheat-sheets/" target="_blank" rel="noreferrer noopener">Your 8+ Free Python Cheat Sheet [Course]</a></li><li><a href="https://blog.finxter.com/python-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know">Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</a></li><li><a href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/" title="Python Functions and Tricks Cheat Sheet" target="_blank" rel="noreferrer noopener">Python Functions and Tricks Cheat Sheet</a></li><li><a href="https://blog.finxter.com/python-interview-questions/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/python-interview-questions/">Python Cheat Sheet: 14 Interview Questions</a></li><li><a href="https://blog.finxter.com/pandas-cheat-sheets/" title="[PDF Collection] 7 Beautiful Pandas Cheat Sheets — Post Them to Your Wall" target="_blank" rel="noreferrer noopener">Beautiful Pandas Cheat Sheets</a></li><li><a href="https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/" title="[Collection] 10 Best NumPy Cheat Sheets Every Python Coder Must Own" target="_blank" rel="noreferrer noopener">10 Best NumPy Cheat Sheets</a></li><li><a href="https://blog.finxter.com/python-list-methods-cheat-sheet-instant-pdf-download/" title="Python List Methods Cheat Sheet [Instant PDF Download]" target="_blank" rel="noreferrer noopener">Python List Methods Cheat Sheet [Instant PDF Download]</a></li><li><a href="https://blog.finxter.com/cheat-sheet-6-pillar-machine-learning-algorithms/" target="_blank" rel="noreferrer noopener" title="[Cheat Sheet] 6 Pillar Machine Learning Algorithms">[Cheat Sheet] 6 Pillar Machine Learning Algorithms</a></li></ul>
</div></div>



<p>To master the most important skill in the next decade, AI engineering, check out the following course. It&#8217;s free and easy to learn but a dangerous skill to have in the age of AI! <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>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://academy.finxter.com/university/an-introduction-to-ai-engineering/"><img loading="lazy" decoding="async" width="1024" height="786" src="https://blog.finxter.com/wp-content/uploads/2024/09/image-12-1024x786.png" alt="" class="wp-image-1671030" srcset="https://blog.finxter.com/wp-content/uploads/2024/09/image-12-1024x786.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/09/image-12-300x230.png 300w, https://blog.finxter.com/wp-content/uploads/2024/09/image-12-768x589.png 768w, https://blog.finxter.com/wp-content/uploads/2024/09/image-12.png 1190w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>


<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Free Course:</strong> <a href="https://academy.finxter.com/university/an-introduction-to-ai-engineering/" data-type="link" data-id="https://academy.finxter.com/university/an-introduction-to-ai-engineering/">A Beginner&#8217;s Guide to AI Engineering (Full Course)</a></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/python-cheat-sheet/">Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</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 Enum Conversion (Ultimate Guide)</title>
		<link>https://blog.finxter.com/python-enum-conversion-ultimate-guide/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Tue, 16 Apr 2024 18:35:27 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Dictionary]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670081</guid>

					<description><![CDATA[<p>💡 Enums (short for enumerations) are a powerful feature in Python that allows for organizing a set of symbolic names (members) bound to unique, constant values. Enums are a convenient way to associate names with constants in a clear and explicit way. Before diving into the conversion methods, let&#8217;s quickly recap the Python enum module. ... <a title="Python Enum Conversion (Ultimate Guide)" class="read-more" href="https://blog.finxter.com/python-enum-conversion-ultimate-guide/" aria-label="Read more about Python Enum Conversion (Ultimate Guide)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-enum-conversion-ultimate-guide/">Python Enum Conversion (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 class="has-global-color-8-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>Enums </strong>(short for enumerations) are a powerful feature in Python that allows for organizing a set of symbolic names (members) bound to unique, constant values. Enums are a convenient way to associate names with constants in a clear and explicit way.</p>



<p>Before diving into the conversion methods, let&#8217;s quickly recap the Python <code>enum</code> module. In this example, <code>Color</code> is an enumeration with three members: <code>RED</code>, <code>GREEN</code>, and <code>BLUE</code>, associated with the values 1, 2, and 3, respectively.</p>



<p><strong>MINIMAL ENUM EXAMPLE: <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;" /> </strong></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="">from enum import Enum

# Define an enum named Color with a few members
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# Accessing members and their values
Color.RED  # &lt;Color.RED: 1>
Color.RED.name  # 'RED'
Color.RED.value  # 1
</pre>



<p>But how do we convert these enums to more common data types and back? Let&#8217;s start with the first:</p>



<h2 class="wp-block-heading">Python Convert Enum to String &#8211; and Back</h2>



<p>Converting an Enum to a string can be particularly useful for display purposes or when the enumeration needs to be serialized into a format that requires text (like JSON). The reverse process is handy when parsing strings to obtain Enum values.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9,12" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# Convert Enum to String
color_string = Color.RED.name

# Convert String to Enum
color_enum = Color[color_string]

print(color_string)  # Outputs: RED
print(color_enum)    # Outputs: Color.RED</pre>



<p>Here, <code>Color.RED.name</code> is used to convert an Enum member to a string. On the flip side, <code>Color[color_string]</code> converts a string back to an Enum member. This is particularly helpful in configurations or environments where only strings are usable.</p>



<h2 class="wp-block-heading">Python Convert Enum to Int &#8211; and Back</h2>



<p>Sometimes, you might need to convert Enum members to integers for indexing, interfacing with C code, or simple arithmetic. Conversely, converting integers back to Enums is vital for maintaining the encapsulation of Enum types.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Convert Enum to Int
color_int = Color.RED.value

# Convert Int to Enum
color_enum_from_int = Color(color_int)

print(color_int)                # Outputs: 1
print(color_enum_from_int)      # Outputs: Color.RED</pre>



<p>In this snippet, <code>Color.RED.value</code> gives the integer associated with <code>Color.RED</code>. To convert this integer back to an Enum, we call <code>Color(color_int)</code>.</p>



<h2 class="wp-block-heading">Python Convert Enum to List &#8211; and Back</h2>



<p>Converting an Enum to a list is useful when you need to perform operations that require sequence data types like iterations, mapping, etc. The reversal doesn&#8217;t apply typically as you wouldn&#8217;t convert a list directly back into an Enum, but you could recreate the Enum if needed.</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=""># Convert Enum to List
color_list = [c for c in Color]

print(color_list)  # Outputs: [&lt;Color.RED: 1>, &lt;Color.GREEN: 2>, &lt;Color.BLUE: 3>]</pre>



<p>This list comprehension iterates over the Enum class, converting it into a list of Enum members.</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/list-comprehension/">List Comprehension in Python — A Helpful Illustrated Guide</a></p>



<h2 class="wp-block-heading">Python Convert Enum to Dict &#8211; and Back</h2>



<p>When dealing with Enum members in a dynamic manner, converting it to a dictionary can be incredibly useful, especially when the names and values are needed directly.</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=""># Convert Enum to Dict
color_dict = {color.name: color.value for color in Color}

# Convert Dict to Enum
class ColorNew(Enum):
    pass

for name, value in color_dict.items():
    setattr(ColorNew, name, value)

print(color_dict)       # Outputs: {'RED': 1, 'GREEN': 2, 'BLUE': 3}
print(ColorNew.RED)     # Outputs: ColorNew.RED</pre>



<p>Here, we first create a dictionary from the Enum, ensuring each name maps to its respective value. To convert it back, we dynamically generate a new Enum class and assign values.</p>



<h2 class="wp-block-heading">Python Convert Enum to JSON &#8211; and Back</h2>



<p>Serialization of Enums into JSON is essential for configurations and network communications where lightweight data interchange formats are used.</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 json

# Convert Enum to JSON
color_json = json.dumps(color_dict)

# Convert JSON to Enum
color_info = json.loads(color_json)
color_enum_from_json = Color[color_info['RED']]

print(color_json)               # Outputs: '{"RED": 1, "GREEN": 2, "BLUE": 3}'
print(color_enum_from_json)     # Outputs: Color.RED</pre>



<p>This example shows how you can use a dictionary representation to convert Enum members into JSON and then parse it back.</p>



<h2 class="wp-block-heading">Python Convert Enum to List of Strings &#8211; and Back</h2>



<p>In some cases, a list of string representations of Enum members may be required, such as for populating dropdowns in GUI frameworks, or for data validation.</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=""># Convert Enum to List of Strings
color_str_list = [color.name for color in Color]

# Convert List of Strings to Enum
color_enum_list = [Color[color] for color in color_str_list]

print(color_str_list)        # Outputs: ['RED', 'GREEN', 'BLUE']
print(color_enum_list)       # Outputs: [&lt;Color.RED: 1>, &lt;Color.GREEN: 2>, &lt;Color.BLUE: 3>]</pre>



<p>This straightforward comprehension allows for quick conversions to and from lists of string representations.</p>



<h2 class="wp-block-heading">Python Convert Enum to Tuple &#8211; and Back</h2>



<p>Tuples, being immutable, serve as a good data structure to hold Enum members when modifications are not required.</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=""># Convert Enum to Tuple
color_tuple = tuple(Color)

# This showcases conversion but typically you won't convert back directly
# However, Enum members can be extracted back from the tuple if needed

print(color_tuple)  # Outputs: (Color.RED, Color.GREEN, Color.BLUE)</pre>



<p>While the reverse is uncommon, extracting specific Enum members from a tuple is straightforward.</p>



<h2 class="wp-block-heading">Python Convert Enum to Literal &#8211; and Back</h2>



<p>Python type hints support literals which can be handy in situations where function parameters are expected to be specific Enum members only.</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 typing import Literal

ColorLiteral = Literal[Color.RED.name, Color.GREEN.name, Color.BLUE.name]

# Example function using this literal
def set_background_color(color: ColorLiteral):
    print(f"Setting background color to {color}")

set_background_color('RED')  # Correct usage

# Conversion back is essentially parsing the literal to the Enum
parsed_color = Color['RED']  # Works as expected

print(parsed_color)  # Outputs: Color.RED</pre>



<p>Here, <code>Literal</code> is a way to ensure type-checking for functions that should only accept specific Enum members in string form.</p>



<h2 class="wp-block-heading">Python Convert Enum to Map &#8211; and Back</h2>



<p>The <code><a href="https://blog.finxter.com/python-map/">map</a></code> function in Python can apply a function over a sequence and is easily demonstrated with Enums.</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=""># Use map to convert Enum to another form
mapped_values = list(map(lambda c: (c.name, c.value), Color))

# Normally you won't convert a map result back to Enum directly
# But you can reconstruct the Enum if needed

print(mapped_values)  # Outputs: [('RED', 1), ('GREEN', 2), ('BLUE', 3)]</pre>



<p>Mapping Enum values to a structure like tuple pairs can facilitate operations such as sorting by either names or values.</p>



<h2 class="wp-block-heading">Python Convert Enum to List of Tuples &#8211; and Back</h2>



<p>This conversion is useful for creating indexed structures from Enums, beneficial in scenarios where a tuple-based lookup is needed.</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=""># Convert Enum to List of Tuples
color_tuples_list = [(color.name, color.value) for color in Color]

# This can directly be used to reconstruct the Enum if needed
class ReconstructedEnum(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(color_tuples_list)              # Outputs: [('RED', 1), ('GREEN', 2), ('BLUE', 3)]
print(ReconstructedEnum.RED)          # Outputs: ReconstructedEnum.RED</pre>



<p>Though direct conversion back isn&#8217;t typical, reconstruction is an option here.</p>



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



<ul class="wp-block-list">
<li><strong>String</strong>: Convert with <code>.name</code> and restore with <code>Enum[name]</code>.</li>



<li><strong>Integer</strong>: Use <code>.value</code> and <code>Enum(value)</code>.</li>



<li><strong>List</strong>: Directly iterate over Enum.</li>



<li><strong>Dictionary</strong>: Comprehensions suit well for conversions; Class redefinition helps in reverse.</li>



<li><strong>JSON</strong>: Utilize dictionaries for intermediate conversions.</li>



<li><strong>List of Strings</strong>: Enum names in a list simplify GUI use.</li>



<li><strong>Tuple</strong>: Direct use for immutable sequence requirements.</li>



<li><strong>Literal</strong>: Enhance type safety.</li>



<li><strong>Map</strong>: Apply transformations with <code>map</code>.</li>



<li><strong>List of Tuples</strong>: Ideal for tuple-based structure requirements.</li>
</ul>



<p>Using Python Enums effectively means understanding how to transform them to and from different types, broadening their usability across various aspects of Python programming.</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-dictionary-comprehension/">Python Dictionary Comprehension: A Powerful One-Liner Tutorial</a></p>
<p>The post <a href="https://blog.finxter.com/python-enum-conversion-ultimate-guide/">Python Enum Conversion (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 One Line For Loop [A Simple Tutorial]</title>
		<link>https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 09 Mar 2024 17:47:43 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<category><![CDATA[Python One-Liners]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=5394</guid>

					<description><![CDATA[<p>Python is powerful &#8212; you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a for loop in a single line of code? This tutorial explores this mission-critical question in all detail. How to Write a For Loop in a Single Line of Python Code? ... <a title="Python One Line For Loop [A Simple Tutorial]" class="read-more" href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" aria-label="Read more about Python One Line For Loop [A Simple Tutorial]">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/">Python One Line For Loop [A Simple 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 is powerful &#8212; you can condense many algorithms into a <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">single line</a> of Python code. </p>



<p>So the natural question arises: <strong>can you write a for loop in a single line of code? </strong></p>



<p>This tutorial explores this mission-critical question in all detail.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python One Line For Loop [A Simple Tutorial]" width="937" height="527" src="https://www.youtube.com/embed/M6XNZ40lRFQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">How to Write a For Loop in a Single Line of Python Code?</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-225-1024x682.png" alt="" class="wp-image-1071437" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-225-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-225-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-225-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-225.png 1055w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>There are two ways of writing a one-liner for loop:</p>



<ul class="wp-block-list">
<li><strong>Method 1</strong>: If the loop body consists of one statement, simply write this statement into the same line: <code>for i in range(10): print(i)</code>. This <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">prints</a> the first 10 numbers to the shell (from 0 to 9). </li>



<li><strong>Method 2: </strong>If the purpose of the loop is to <a href="https://blog.finxter.com/how-to-create-a-python-list/" data-type="post" data-id="10436" target="_blank" rel="noreferrer noopener">create a list</a>, use <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">list comprehension</a> instead: <code>squares = [i**2 for i in range(10)]</code>. The code squares the first ten numbers and stores them in the <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> <code>squares</code>. </li>
</ul>



<p>Let&#8217;s have a look at both variants in more detail.</p>



<p><strong>Check out my new Python book <a title="https://amzn.to/2WAYeJE" href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener">Python One-Liners</a></strong> (Amazon Link).</p>



<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it&#8217;s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>


<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>


<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>



<p><strong>Publisher Link</strong>: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>



<p>Enough promo, let&#8217;s dive into the first method&#8212;the profane&#8230;</p>



<h2 class="wp-block-heading">Method 1: Single-Line For Loop</h2>



<p class="has-global-color-8-background-color has-background">Just writing the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="post" data-id="4596" target="_blank">for loop</a> in a single line is the most direct way of accomplishing the task. After all, Python doesn&#8217;t need the indentation levels to resolve ambiguities when the loop body consists of only one line.</p>



<p>Say, we want to write the following for loop in a single line of 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="">>>> for i in range(10):
	print(i)

	
0
1
2
3
4
5
6
7
8
9</pre>



<p>We can easily get this done by writing the command into a single line of 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="">>>> for i in range(10): print(i)

0
1
2
3
4
5
6
7
8
9</pre>



<p>While this answer seems straightforward, the interesting question is: <strong><em>can we write a more complex for loop that has a longer loop body in a single line?</em></strong></p>



<p>This is much more difficult. While it&#8217;s possible to condense complicated algorithms in a single line of code, there&#8217;s no general formula. </p>



<p>If you&#8217;re interested in compressing whole algorithms into a single line of code, check out <a href="https://blog.finxter.com/10-python-one-liners/">this art</a><a href="https://blog.finxter.com/10-python-one-liners/" target="_blank" rel="noreferrer noopener">i</a><a href="https://blog.finxter.com/10-python-one-liners/">cle with 10 Python one-liners</a> that fit into a single tweet. </p>



<p>Suppose, you have the following more complex loop:</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="">for i in range(10):
    if i&lt;5:
        j = i**2
    else:
        j = 0    
    print(j)</pre>



<p>This generates the output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0
1
4
9
16
0
0
0
0
0</pre>



<p>Can we compress it into a single line? </p>



<p>The answer is <strong>yes</strong>! Check out the following code snippet:</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="">for i in range(10): print(i**2 if i&lt;5 else 0)</pre>



<p>This generates the same output as our multi-line <code>for</code> loop. </p>



<p>As it turns out, we can use the ternary operator in Python that allows us to compress an <code>if</code> statement into a single line. </p>



<p><a href="https://blog.finxter.com/if-then-else-in-one-line-python/">Check out this tutorial on our blog if you want to learn more about the exciting ternary operator in Python</a>. </p>



<p>The <strong>ternary operator</strong> is very intuitive: just read it from left to right to understand its meaning. </p>



<p>In the loop body <code>print(i**2 if i&lt;5 else 0)</code> we <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print</a> the square number <code>i**2</code> if i is smaller than 5, otherwise, we print 0. </p>



<p>Let&#8217;s explore an alternative <a href="https://blog.finxter.com/the-top-18-best-python-tricks/" data-type="post" data-id="4358" target="_blank" rel="noreferrer noopener">Python trick</a> that&#8217;s very popular among Python masters:</p>



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


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-1024x576.jpg" alt="List Comprehension" class="wp-image-8559" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/05/listcomp-768x432.jpg 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Being hated by newbies, experienced Python coders can’t live without this awesome Python feature called <em><a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">list comprehension</a></em>.</p>



<p>Say, we want to create a list of squared numbers. The traditional way would be to write something along these lines:</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="">squares = []

for i in range(10):
    squares.append(i**2)
    
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre>



<p>We create an <a href="https://blog.finxter.com/how-to-check-if-a-python-list-is-empty/" data-type="post" data-id="9090" target="_blank" rel="noreferrer noopener">empty list</a> <code>squares</code> and successively add another square number starting from 0**2 and ending in 9**2. </p>



<p>Thus, the result is the list <code>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</code>. </p>



<p>List comprehension condenses this into a single line of code&#8211;that is also readable, more efficient, and concise.</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([i**2 for i in range(10)])</pre>



<p>This line accomplishes the same output with much fewer bits.</p>



<p>A thorough <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">tutorial of list comprehension can be found at this illustrated blog resource</a>.</p>



<p>Also, feel free to watch the video in my list comprehension tutorial:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="A Simple Introduction to List Comprehension in Python" width="937" height="527" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>List comprehension is a compact way of creating lists. The simple formula is <code>[ expression + context ]</code>.</strong></p>



<ul class="wp-block-list">
<li><strong>Expression: </strong>What to do with each list element?</li>



<li><strong>Context: </strong>What list elements to select? It consists of an arbitrary number of for and if statements.</li>
</ul>



<p><strong>The first part is the expression.</strong> In the example above, it was the expression <code>i**2</code>. Use any variable in your expression that you have defined in the context within a loop statement.</p>



<p><strong>The second part is the context</strong>. In the example above, it was the expression <code>for i in range(10)</code>. The context consists of an arbitrary number of <code>for</code> and <code>if</code> clauses. The single goal of the context is to define (or restrict) the sequence of elements on which we want to apply the expression. </p>



<h2 class="wp-block-heading">Method 3: Python One Line For Loop With If</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="684" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-227-1024x684.png" alt="" class="wp-image-1071454" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-227-1024x684.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-227-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-227-768x513.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-227.png 1053w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>You can also modify the list comprehension statement by restricting the context with another <code>if</code> statement:</p>



<p><strong>Problem</strong>: Say, we want to create a list of squared numbers&#8212;but you only consider even and ignore odd numbers. </p>



<p><strong>Example</strong>: The multi-liner way would be the following.</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="">squares = []

for i in range(10):
    if i%2==0:
        squares.append(i**2)
    
print(squares)
# [0, 4, 16, 36, 64]
</pre>



<p>You create an empty list <code>squares</code> and successively add another square number starting from 0**2 and ending in 8**2&#8212;but only considering the even numbers 0, 2, 4, 6, 8. </p>



<p>Thus, the result is the list <code>[0, 4, 16, 36, 64]</code>. </p>



<p>Again, you can use list comprehension <code>[i**2 for i in range(10) <strong>if i%2==0</strong>]</code> with a restrictive <code>if</code> clause (in bold) in the context part to compress this in a single line of Python code.</p>



<p>See here:</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([i**2 for i in range(10) if i%2==0])
# [0, 4, 16, 36, 64]</pre>



<p>This line accomplishes the same output with much fewer bits.</p>



<p><strong>Related Article</strong>: <a href="https://blog.finxter.com/python-one-line-for-loop-with-if/" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/python-one-line-for-loop-with-if/">Python One-Line For Loop With If</a></p>



<h2 class="wp-block-heading">Related Questions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="866" height="577" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-228.png" alt="" class="wp-image-1071457" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-228.png 866w, https://blog.finxter.com/wp-content/uploads/2023/01/image-228-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-228-768x512.png 768w" sizes="auto, (max-width: 866px) 100vw, 866px" /></figure>
</div>


<p>Let&#8217;s dive into some related questions that might come to your mind. </p>



<h3 class="wp-block-heading">What&#8217;s a Generator Expression? </h3>



<p>A <a href="http://wiki.python.org/moin/Generators" target="_blank" rel="noreferrer noopener">generator expression</a> is a simple tool to generate iterators. </p>



<p>If you use a <code>for</code> loop, you often iterate over an <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterator</a>. For instance, a generator expression does not explicitly create a list in memory. </p>



<p>Instead, it dynamically generates the next item in the iterable as it goes over the iterable. </p>



<p>We used a <a href="https://blog.finxter.com/how-to-use-generator-expressions-in-python-dictionaries/" data-type="post" data-id="7502" target="_blank" rel="noreferrer noopener">generator expression</a> in the <code><a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print()</a></code> statement above:</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(i**2 if i&lt;5 else 0)</pre>



<p>There are no squared brackets around the generator expression as it&#8217;s the case for list comprehensions.</p>



<h3 class="wp-block-heading">How to Create a Nested For Loop in One Line?</h3>



<p>We cannot write a simple nested for loop in one line of Python.</p>



<p>Say, you want to write a <a href="https://blog.finxter.com/how-to-write-a-nested-for-loop-in-one-line-python/" data-type="post" data-id="11859" target="_blank" rel="noreferrer noopener">nested <code>for</code> loop</a> like the following in one line of Python 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="">for i in range(3):
    for j in range(3):
        print((i,j))

'''
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
'''</pre>



<p>When trying to write this into a single line of code, we get a syntax error:</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="">for i in range(3): for j in range(3): print((i,j))
# Syntax Error</pre>



<p>You can see the error message in the following screenshot:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="764" height="290" src="https://blog.finxter.com/wp-content/uploads/2019/12/grafik.png" alt="" class="wp-image-5398" srcset="https://blog.finxter.com/wp-content/uploads/2019/12/grafik.png 764w, https://blog.finxter.com/wp-content/uploads/2019/12/grafik-300x114.png 300w" sizes="auto, (max-width: 764px) 100vw, 764px" /></figure>
</div>


<p>However, we can create a nested list comprehension statement.</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([(i,j) for i in range(3) for j in range(3)])
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),
# (1, 2), (2, 0), (2, 1), (2, 2)]</pre>



<p>This only leads to a slightly more complex context part <code>for i in range(3) for j in range(3)</code>. But it&#8217;s manageable.</p>



<h2 class="wp-block-heading">Where to Go From Here</h2>



<p>Knowing small <a rel="noreferrer noopener" href="https://blog.finxter.com/10-python-one-liners/" target="_blank">Python one-liner tricks</a> such as list comprehension and single-line <code>for</code> loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.</p>



<p>If you want to learn the language Python by heart, join my <a href="https://blog.finxter.com/subscribe/">free Python email course</a>. </p>






<p>It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.</p>



<h2 class="wp-block-heading">Python One-Liners Book: Master the Single Line First!</h2>



<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>



<div class="wp-block-image"><figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-300x277.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-768x708.jpg 768w" sizes="auto, (max-width: 512px) 100vw, 512px" /></a></figure></div>



<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>



<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>



<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You&#8217;ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p>



<p>You&#8217;ll also learn how to:</p>



<ul class="wp-block-list"><li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li><li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li><li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li><li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li><li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li></ul>



<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.</p>



<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>



<h2 class="wp-block-heading">Programmer Humor &#8211; Blockchain</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uploads/2022/07/image-31-213x300.png 213w" sizes="auto, (max-width: 280px) 100vw, 280px" /><figcaption><em>&#8220;Blockchains are like grappling hooks, in that it&#8217;s extremely cool when you encounter a problem for which they&#8217;re the right solution, but it happens way too rarely in real life.&#8221;</em> <strong>source </strong>&#8211; <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div><p>The post <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/">Python One Line For Loop [A Simple 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 Create a Python List?</title>
		<link>https://blog.finxter.com/how-to-create-a-python-list/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 09 Mar 2024 17:45:31 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=10436</guid>

					<description><![CDATA[<p>Definition Lists: A Python list is an ordered sequence of arbitrary Python objects. It is a mutable object by itself so, unlike Python sets, you can modify a Python list. In this article, you&#8217;ll learn everything you need to know on how to create Python lists. Overview &#8212; Creating a List in Python There are ... <a title="How to Create a Python List?" class="read-more" href="https://blog.finxter.com/how-to-create-a-python-list/" aria-label="Read more about How to Create a Python List?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-a-python-list/">How to Create a Python List?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Create a Python List?" width="937" height="527" src="https://www.youtube.com/embed/qXOFngx0bQU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>Definition Lists</strong>: A <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">Python list</a> is an ordered sequence of arbitrary Python objects. It is a mutable object by itself so, unlike<a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Sets – with Harry Potter Examples"> Python sets</a>, you can modify a Python list.</p>



<p><em>In this article, you&#8217;ll learn everything you need to know on <strong>how to create Python lists</strong>.</em></p>



<h2 class="wp-block-heading">Overview &#8212; Creating a List in Python</h2>



<p>There are many ways of creating a list in Python. Let&#8217;s get a quick overview in the following table:</p>



<figure class="wp-block-table is-style-stripes"><table><thead><tr><th>Code</th><th>Description</th></tr></thead><tbody><tr><td><code>[]</code></td><td><strong>Square bracket</strong>: Initializes an empty list with zero elements. You can add elements later.</td></tr><tr><td><code>[x1, x2, x3, … ]</code></td><td><strong>List display:</strong> Initializes an empty list with elements <code>x1</code>, <code>x2</code>, <code>x3</code>, &#8230; For example, <code>[1, 2, 3]</code> creates a list with three integers 1, 2, and 3.</td></tr><tr><td><code>[expr1, expr2, ... ]</code></td><td><strong>List display with expressions</strong>: Initializes a list with the result of the expressions <code>expr1</code>, <code>expr2</code>, &#8230; For example, <code>[1+1, 2-1]</code> creates the list <code>[2, 1]</code>. </td></tr><tr><td><code>[expr for var in iter]</code></td><td><strong>List comprehension</strong>: applies the expression <code>expr</code> to each element in an iterable.</td></tr><tr><td><code>list(iterable)</code></td><td><strong>List constructor</strong> that takes an iterable as input and returns a new list.</td></tr><tr><td><code>[x1, x2, ...] * n</code></td><td><strong>List multiplication</strong> creates a list of n concatenations of the list object. For example <code>[1, 2] * 2 == [1, 2, 1, 2]</code>.</td></tr></tbody></table></figure>



<p></p>



<p>Let&#8217;s dive into some more specific ways to create various forms of lists in <a href="https://blog.finxter.com/python-crash-course/" title="Python Programming Tutorial [+Cheat Sheets]" target="_blank" rel="noreferrer noopener">Python</a>. </p>



<p><strong><em>BELOW I&#8217;LL GIVE YOU A PDF CHEAT SHEET OF THE MOST IMPORTANT PYTHON LIST METHODS.</em></strong> So keep reading!</p>



<h2 class="wp-block-heading">Python Create List of Size</h2>



<p><strong>Problem</strong>: Given an integer <code>n</code>. How to initialize a list with <code>n</code> placeholder elements?</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=""># n=0 --> []
# n=1 --> [None]
# n=5 --> [None, None, None, None, None]</pre>



<p><strong>Solution</strong>: Use the <a href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank" rel="noreferrer noopener" title="How to Concatenate Lists in Python? [Interactive Guide]">list concatenation</a> operation <code>*</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="">n = 5
lst = [None] * n
print(lst)
# [None, None, None, None, None]</pre>



<p>You can modify the element <code>n</code> as you like. For a detailed discussion on this topic, please visit my blog tutorial on <a href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" title="How to Create a Python List of Size n?" target="_blank" rel="noreferrer noopener">How to Create a List with a Specific Size n?</a> The tutorial also contains many visualizations to teach you the ins and outs of this method (and gives you some powerful alternatives). </p>



<h2 class="wp-block-heading">Python Create List of Strings</h2>



<p>You can use the previous method to create a list of n <a href="https://blog.finxter.com/python-string-to-list-the-most-pythonic-way/" target="_blank" rel="noreferrer noopener" title="Python String to List | The Most Pythonic Way">strings</a>:</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="">n = 3
lst = ['xyz'] * n
print(lst)
# ['xyz', 'xyz', 'xyz']</pre>



<p>But do you want to create a list of numbers?</p>



<h2 class="wp-block-heading">Python Create List of Numbers</h2>



<p>Simply replace the default strings with the default numbers:</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="">n = 3
lst = [1] * n
print(lst)
# [1, 1, 1]</pre>



<p>A special case is the number:</p>



<h2 class="wp-block-heading">Python Create List of Zeros</h2>



<p>This creates a list of zeros:</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="">n = 3
lst = [0] * n
print(lst)
# [0, 0, 0]</pre>



<p>But what if you want to create a list of consecutive numbers 0, 1, 2, &#8230;?</p>



<h2 class="wp-block-heading">Python Create List from Range</h2>



<p>To create a list of consecutive numbers from <code>x</code> to <code>y</code>, use the <code><a href="https://blog.finxter.com/daily-python-puzzle-range-indexing/" title="The Range Function and Indexing in Python">range(x, y)</a></code> built-in Python function. This only returns a <code>range</code> object which is an iterable. But you can convert the iterable to a list using the <code>list(...)</code> constructor:</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(list(range(2, 4)))
# [2, 3]

print(list(range(2, 6)))
# [2, 3, 4, 5]

print(list(range(2, 10, 2)))
# [2, 4, 6, 8]</pre>



<p>You can see that the second argument (the <code>stop</code> index) is not included in the range sequence. The third argument of the <code>range(start, stop, step)</code> function is the optional step size that allows you to skip <code>step</code> numbers of the series of continuous numbers.</p>



<h2 class="wp-block-heading">Python Create List from 0 to 100</h2>



<p>A special situation arises if you want to create a list from 0 to 100 (included). In this case, you simply use the <code>list(range(0, 101))</code> function call. As <code>stop</code> argument, you use the number 101 because it&#8217;s excluded from the final series. </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(list(range(0, 101)))
# [0, 1, ..., 100]

print(list(range(101)))
# [0, 1, ..., 100]</pre>



<p>It&#8217;s actually not necessary to give the default start index 0, so you can just skip it.</p>



<h2 class="wp-block-heading">Python Create List with For Loop</h2>



<p>To create a list with a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">for loop</a>, you first initialize the empty list, and then subsequently append an element to 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="">lst = []
for x in range(10):
    # Append any initial element here:
    lst.append(x)

print(lst)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>



<p>You can learn more about the <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop [A Simple Tutorial]">single-line for loop in this article</a>. </p>



<h2 class="wp-block-heading">Python Create List of Lists</h2>



<p>However, there&#8217;s a small problem if you want to create a list with mutable objects (such as a<a href="https://blog.finxter.com/python-list-of-lists/" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python" target="_blank" rel="noreferrer noopener"> list of lists</a>):</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="">lst = [[]] * n
print(lst)
# [[], [], [], [], []]

lst[2].append(42)

print(lst)
# [[42], [42], [42], [42], [42]]</pre>



<p>Changing one list element changes all list elements because all list elements refer to the same list object in memory:</p>



<iframe loading="lazy" src="https://pythontutor.com/iframe-embed.html#code=n%20%3D%205%0Alst%20%3D%20%5B%5B%5D%5D%20*%20n%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D%5D%0A%0Alst%5B2%5D.append%2842%29%0A%0Aprint%28lst%29%0A%23%20%5B%5B42%5D,%20%5B42%5D,%20%5B42%5D,%20%5B42%5D,%20%5B42%5D%5D&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=1&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500" frameborder="0"> </iframe>



<p>The solution is to use list comprehension (<a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">see my detailed blog tutorial on list comprehension for a complete guide</a>):</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="">lst = [[] for _ in range(n)]
print(lst)
# [[], [], [], [], []]

lst[2].append(42)
print(lst)
# [[], [], [42], [], []]</pre>



<p>In the following visualization, you can see how each element now refers to an independent list object in memory:</p>



<iframe loading="lazy" src="https://pythontutor.com/iframe-embed.html#code=n%20%3D%205%0Alst%20%3D%20%5B%5B%5D%20for%20_%20in%20range%28n%29%5D%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D,%20%5B%5D%5D%0A%0Alst%5B2%5D.append%2842%29%0Aprint%28lst%29%0A%23%20%5B%5B%5D,%20%5B%5D,%20%5B42%5D,%20%5B%5D,%20%5B%5D%5D&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500" frameborder="0"> </iframe>



<p><em><strong>Exercise</strong>: Run the visualization and convince yourself that only one element is modified! Why is this the case?</em></p>



<h2 class="wp-block-heading">Python Create List of Tuples</h2>



<p>A similar approach can be used to create a list of tuples instead of a<a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python"> list of lists</a>. </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="">n = 5
lst = [() for _ in range(n)]
print(lst)

lst[2] = (1, 2, 3)
print(lst)

'''
[(), (), (), (), ()]
[(), (), (1, 2, 3), (), ()]
'''</pre>



<p>You first initialize the list with empty tuples. <a href="https://blog.finxter.com/python-tuple-to-integer/" target="_blank" rel="noreferrer noopener" title="Python Tuple to Integer">Tuples </a>are immutable so you cannot change them. But you can overwrite each list element with a new tuple like you did in the example with the third element and tuple <code>(1, 2, 3)</code>. </p>



<h2 class="wp-block-heading">Python Create Equally Spaced List</h2>



<p>To create an equally spaced list, use the <a href="https://blog.finxter.com/np-linspace/" title="How to Use np.linspace() in Python? A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener"><code>np.linspace()</code> function</a> of the NumPy library. Here&#8217;s a short tutorial on the matter:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Use np.linspace() in Python? A Helpful Illustrated Guide" width="937" height="527" src="https://www.youtube.com/embed/vPZwZfd-aNY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Let&#8217;s get a quick overview first.</p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/05/linspace-1024x576.jpg" alt="NumPy np.linspace()" class="wp-image-9500" style="width:768px;height:432px" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/linspace-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/05/linspace-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/05/linspace-768x432.jpg 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Let&#8217;s look at the three most common arguments in more detail first: <code>start</code>, <code>stop</code> and <code>num</code>. Here&#8217;s what the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html">official NumPy docs</a> has to say: </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="">numpy.linspace(start, stop, num=50)</pre>



<p><em>Return evenly spaced numbers over a specified interval. Returns num&nbsp;evenly-spaced samples. The endpoint of the interval can optionally be excluded.</em></p>



<p><strong>Note</strong>: as the name suggests, <code>np.linspace</code> returns numbers that are <em>linearly-spaced</em> apart. Thus they are all the same distance apart from one another (think of points on a line). </p>



<p>From the definition, it follows that <code>np.linspace(-3, 3)</code> will give us 50 numbers evenly spaced apart in the interval <code>[-3, 3]</code>.&nbsp; <br>Let&#8217;s check this with some code.</p>



<p></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 = np.linspace(-3, 3)

>>> type(A)
numpy.ndarray

# Number of elements in A
>>> len(A)
50

# First element of A
>>> A[0]
-3.0

# Last element of A
>>> A[-1]
3.0

# The difference between every value is the same: 0.12244898
>>> np.diff(A)
array([0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,
       0.12244898, 0.12244898, 0.12244898, 0.12244898])</pre>



<p>If we want only 10 samples between -3 and 3, we set <code>num=10</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="">>>> B = np.linspace(-3, 3, num=10)

# B only contains 10 elements now
>>> len(B)
10</pre>



<p>But what if you want to initialize your list with random elements?</p>



<h2 class="wp-block-heading">Python Create List of Random Elements</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Create a List of Random Numbers — The Most Pythonic Way" width="937" height="527" src="https://www.youtube.com/embed/b2v2E1bmE-U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Do you want to initialize a list with some random numbers? Next, I&#8217;ll show you four different way of accomplishing this&#8212;along with a short discussion about <em>&#8220;the most Pythonic way&#8221;</em>. </p>



<p><strong>Problem</strong>: Given an integer <code>n</code>. Create a list of <code>n</code> elements in a certain interval (example interval: <em>[0, 20]</em>). </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=""># n = 5 --> [2, 3, 1, 4, 3]
# n = 3 --> [10, 12, 1]
# n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]</pre>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/07/random-1024x576.jpg" alt="" class="wp-image-10536" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/random-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/07/random-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/07/random-768x432.jpg 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>Solution</strong>: Here&#8217;s a quick overview on how you can create a list of random numbers:</p>



<ul class="wp-block-list">
<li><strong>Method 1</strong>: <code>[random.random() for _ in range(10)]</code> to create a list of random floats.</li>



<li><strong>Method 2</strong>: <code>[random.randint(0, 999) for _ in range(10)]</code> to create a list of random ints. </li>



<li><strong>Method 3</strong>: <code>randlist = []; for _ in range(10): randlist.append(random.randint(0, 99))</code> to create a list of random ints.</li>



<li><strong>Method 4</strong>: <code>randlist = random.sample(range(20), 10)</code> to create a list of random ints.</li>
</ul>



<p></p>



<h2 class="wp-block-heading">Python Create List of Lists from Zip</h2>



<p class="has-luminous-vivid-amber-background-color has-background"><strong>Short answer</strong>: Per default, the <code>zip()</code> function returns a zip object of tuples. To obtain a <em>list of lists</em> as an output, use the list comprehension statement <code>[list(x) for x in zip(l1, l2)]</code> that converts each tuple to a list and stores the converted lists in a new nested list object.</p>



<p><em>Intermediate Python coders know the <code>zip()</code> function. But if you&#8217;re like me, you&#8217;ve often cursed the output of the zip function: first of all, it&#8217;s a zip object (and not a list), and, second, the individual zipped elements are tuples. But what if you need a list of lists as output?</em></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="python zip list of lists instead list of tuples" width="937" height="527" src="https://www.youtube.com/embed/MM1PBzZjmh0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>Problem</strong>: Given a number of lists <code>l1, l2, ...</code>. How ot <a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" target="_blank" rel="noreferrer noopener" title="Python Ziiiiiiip! [A helpful guide]">zip </a>the i-th elements of those lists together and obtain a list<a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python"> of lists</a>?</p>



<p><strong>Example</strong>: Given two lists <code>[1, 2, 3, 4]</code> and <code>['Alice', 'Bob', 'Ann', 'Liz']</code> and you want the list of lists <code>[[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]</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="">l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz']
# ... calculate result ...
# Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]</pre>



<p></p>



<h2 class="wp-block-heading">Python Create List a-z</h2>



<p>To create a list with all characters <code>'a'</code>, <code>'b'</code>, &#8230;, <code>'z'</code>, you can use the <code>list()</code> constructor on the <code>string.ascii_lowercase</code> variable:</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 string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> list(string.ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']</pre>



<p>The <code>list()</code> constructor creates a new list and place all elements in the iterable into the new list. A string is an iterable with character elements. Thus, the result is a list of lowercase characters.</p>



<h2 class="wp-block-heading">Python Create List of Dictionaries</h2>



<p>Say, you have a <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a><code>{0: 'Alice', 1: 'Bob'}</code> and you want to create a <a href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank" rel="noreferrer noopener" title="How to Create a List of Dictionaries in Python?">list of dictionaries</a> with copies of the original dictionary: <code>[{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</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="">d = {0: 'Alice', 1: 'Bob'}

dicts = [{**d} for _ in range(3)]
print(dicts)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>



<p>You use list comprehension with a &#8220;throw-away&#8221; loop variable underscore <code>_</code> to create a list of 3 elements. You can change the value 3 if you need more or fewer elements in your list. </p>



<p>The expression <code>{**d}</code> <a href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank" rel="noreferrer noopener" title="What is the Asterisk / Star Operator (*) in Python?">unpacks </a>all (key, value) pairs from the original dictionary <code>d</code> into a new dictionary. </p>



<p>The resulting list contains copies of the original dictionary. If you change one, the others won&#8217;t see that change:</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="">dicts[0][2] = 'Frank'
print(dicts)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>



<p>Only the first dictionary in the list contains the new key value pair <code>(2: 'Frank')</code> which proves that the dictionaries don&#8217;t point to the same object in memory. This would be the case if you&#8217;d use the following method of <a href="https://blog.finxter.com/python-list-copy/" target="_blank" rel="noreferrer noopener" title="Python List copy()">copying a list</a> with a single dictionary:</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="">d2 = {0: 'Alice', 1: 'Bob'}

dicts2 = [d2] * 3
print(dicts2)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>



<p>The method looks right but all three dictionaries are essentially the same:</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="">dicts2[0][2] = 'Frank'
print(dicts2)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}]
</pre>



<p>If you change one, you change all.</p>



<p>You can see this effect yourself in the following memory visualizer tool:</p>



<iframe loading="lazy" src="https://pythontutor.com/iframe-embed.html#code=d2%20%3D%20%7B0%3A%20'Alice',%201%3A%20'Bob'%7D%0A%0Adicts2%20%3D%20%5Bd2%5D%20*%203%0Aprint%28dicts2%29%0A%0Adicts2%5B0%5D%5B2%5D%20%3D%20'Frank'%0Aprint%28dicts2%29&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=1&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500" frameborder="0"> </iframe>



<p><em><strong>Exercise</strong>: change the method to the correct one so that the change affects only the first dictionary!</em></p>



<h2 class="wp-block-heading">Python Create List from DataFrame</h2>



<p>To create a list from a <a href="https://blog.finxter.com/tilde-python-pandas-dataframe/" title="Tilde Python Pandas DataFrame" target="_blank" rel="noreferrer noopener">Pandas DataFrame</a>, use the method <code>df.values.tolist()</code> on your DataFrame object <code>df</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 pandas as pd

incomes = {'Name': ['Alice','Bob','Ann'],
           'Income': [2000, 3000, 9000]}

df = pd.DataFrame(incomes)

lst = df.values.tolist()
print(lst)
# [['Alice', 2000], ['Bob', 3000], ['Ann', 9000]]</pre>



<p>You can see that the output is a <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python">list of lists</a> in this example. If you need to improve your Pandas skills, <a href="https://blog.finxter.com/pandas-cheat-sheets/" title="[PDF Collection] 7 Beautiful Pandas Cheat Sheets — Post Them to Your Wall" target="_blank" rel="noreferrer noopener">check out the most beautiful Python Pandas Cheat Sheets. </a></p>



<h2 class="wp-block-heading">Python Create List from NumPy Array</h2>



<p>To convert a <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">NumPy </a>array <code>a</code> to a list, use the <code>a.tolist()</code> method on the array object. If the NumPy array is multi-dimensional, a <a href="https://blog.finxter.com/how-does-nested-list-comprehension-work-in-python/" target="_blank" rel="noreferrer noopener" title="How Does Nested List Comprehension Work in Python?">nested list</a> is created:</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

a = np.array([[1, 2, 3],
              [4, 5, 6]])

l = a.tolist()
print(l)
# [[1, 2, 3], [4, 5, 6]]</pre>



<p>The resulting list is a nested list of lists.</p>



<h2 class="wp-block-heading">Python Create List Copy</h2>



<p>Surprisingly, even advanced Python coders don&#8217;t know the details of the <code>copy()</code> method of Python lists. Time to change that!</p>



<p><strong>Definition and Usage</strong>: The <code>list.copy()</code> method copies all <code>list</code> elements into a new list. The new list is the return value of the method. It&#8217;s a shallow copy&#8212;you copy only the object references to the list elements and not the objects themselves.</p>



<p>Here&#8217;s a short 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="">>>> lst = [1, 2, 3]
>>> lst.copy()
[1, 2, 3]</pre>



<p>In the first line, you create the list <code>lst</code> consisting of three integers. You then create a new list by copying all elements.</p>



<p><strong>Syntax</strong>: You can call this method on each list object in Python. Here&#8217;s the syntax:</p>



<p><code>list.copy()</code></p>



<p><strong>Arguments:</strong> The method doesn&#8217;t take any argument.</p>



<p><strong>Return value:</strong> The method <code>list.clear()</code> returns a <code>list</code> object by copying references to all objects in the original list.</p>



<p><strong>Video:</strong></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python List copy()" width="937" height="527" src="https://www.youtube.com/embed/VhLrz7ivZbc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>Related articles:</strong></p>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">The Ultimate Guide to Python Lists</a></li>
</ul>



<p>Here&#8217;s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.pdf" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="670" height="870" src="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.jpg" alt="" class="wp-image-7544" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.jpg 670w, https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet-231x300.jpg 231w" sizes="auto, (max-width: 670px) 100vw, 670px" /></a></figure>
</div>


<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-vivid-cyan-blue-background-color has-background wp-element-button" href="https://blog.finxter.com/wp-content/uploads/2020/04/Python-List-Methods-Cheat-Sheet.pdf" style="border-radius:9px" target="_blank" rel="noreferrer noopener">Instant PDF Download [100% FREE]</a></div>
</div>



<p><a href="https://blog.finxter.com/python-list-copy/" target="_blank" rel="noreferrer noopener" title="Python List copy()">You can read more about the <code>list.copy()</code> method in our comprehensive guide on this blog. </a></p>



<h2 class="wp-block-heading">Python Create List from Map</h2>



<p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" target="_blank" rel="noreferrer noopener" title="Mastering the Python Map Function [+Video]"><code>map</code> object</a>. How to create a list? </p>



<p>The answer is straight-forward&#8212;use the <code>list()</code> constructor! 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="">lst = [1, 2, 3]

m = map(str, lst)
print(m)
# &lt;map object at 0x000001E71198B438>

l = list(m)
print(l)
# ['1', '2', '3']</pre>



<p>The resulting list is a list of strings and it contains all elements in the map iterable <code>m</code>. </p>



<p></p>



<p></p>



<p></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-a-python-list/">How to Create a Python List?</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 Create a Pandas DataFrame from a Series</title>
		<link>https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-a-series/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 16 Feb 2024 10:55:09 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1655073</guid>

					<description><![CDATA[<p>💡 Problem Formulation: When working with data in Python, it&#8217;s common to transition between Series and DataFrame objects from the pandas library. A Series is essentially a column, and at times you may need to transform this into a DataFrame &#8211; whether it&#8217;s to join with other data sets or perform operations that require a ... <a title="5 Best Ways to Create a Pandas DataFrame from a Series" class="read-more" href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-a-series/" aria-label="Read more about 5 Best Ways to Create a Pandas DataFrame from a Series">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-a-series/">5 Best Ways to Create a Pandas DataFrame from a Series</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"><b><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;" /> Problem Formulation:</b> When working with data in Python, it&#8217;s common to transition between Series and DataFrame objects from the pandas library. A Series is essentially a column, and at times you may need to transform this into a DataFrame &#8211; whether it&#8217;s to join with other data sets or perform operations that require a DataFrame structure. For instance, you might start with a Series representing a column of temperature readings and want to create a DataFrame from this Series with labeled indices as rows.</p>



<h2 class="wp-block-heading">Method 1: Using DataFrame Constructor</h2>


<p class="has-global-color-8-background-color has-background">The DataFrame constructor in pandas is the most straightforward way to create a DataFrame from a Series. It takes a variety of iterable data structures, including a Series, and transforms them into a DataFrame. The index of the Series becomes the index of the DataFrame, and you can specify the column name for the new DataFrame.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Create a series
temperature_series = pd.Series([21, 23, 24, 22, 25], name='Temperature')

# Convert the series to a dataframe
temperature_df = pd.DataFrame(temperature_series)
</pre>


<p>Output:</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="">   Temperature
0           21
1           23
2           24
3           22
4           25
</pre>


<p>This code snippet demonstrates taking a pandas Series of temperature readings and converting it into a DataFrame with the Series name as the column header. The zeros-based integer index of the Series is preserved in the DataFrame.</p>



<h2 class="wp-block-heading">Method 2: Using series.to_frame()</h2>


<p class="has-global-color-8-background-color has-background">The <code>to_frame()</code> method is a Series method that is used to convert a Series into a DataFrame. It is particularly useful when you want to quickly turn a Series into a DataFrame with a single method call. By default, the Series name becomes the column name in the resulting DataFrame, and the Series index becomes the DataFrame index.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Create a series
scores_series = pd.Series([89, 92, 78, 85], name='Scores')

# Convert the series to a dataframe
scores_df = scores_series.to_frame()
</pre>


<p>Output:</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="">   Scores
0      89
1      92
2      78
3      85
</pre>


<p>This code snippet shows the conversion of a Series containing student scores into a DataFrame. The use of <code>to_frame()</code> creates a DataFrame with the index and column name retained from the Series.</p>



<h2 class="wp-block-heading">Method 3: Assigning Series to DataFrame Columns</h2>


<p class="has-global-color-8-background-color has-background">Creating a new column in an empty DataFrame and assigning a Series to it allows for the creation of a DataFrame from a Series. This method offers additional control, as you can set the column name directly upon assignment, and it is particularly handy when adding multiple series as columns to an initially empty DataFrame.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Create a series
weather_series = pd.Series(['Sunny', 'Cloudy', 'Rain', 'Fog'], name='Weather')

# Initialize an empty dataframe and assign the series as a new column
weather_df = pd.DataFrame()
weather_df['Weather'] = weather_series
</pre>


<p>Output:</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="">  Weather
0   Sunny
1  Cloudy
2    Rain
3     Fog
</pre>


<p>In this example, we begin with a Series of weather conditions and then create an empty DataFrame. We then add the Series to the new DataFrame as a column, which is given the name &#8216;Weather&#8217; (same as the Series name).</p>



<h2 class="wp-block-heading">Method 4: Using a Dictionary of Series</h2>


<p class="has-global-color-8-background-color has-background">You can also create a DataFrame from a dictionary where the keys are column names and the values are Series. This method is particularly useful when creating a DataFrame with multiple columns from multiple Series, because each Series can be simultaneously converted into a DataFrame and combined with others.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Create series for each column
height_series = pd.Series([5.5, 6.1, 5.7], name='Height')
weight_series = pd.Series([165, 180, 150], name='Weight')

# Create a dataframe from a dictionary of series
person_df = pd.DataFrame({'Height': height_series, 'Weight': weight_series})
</pre>


<p>Output:</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="">   Height  Weight
0     5.5     165
1     6.1     180
2     5.7     150
</pre>


<p>This snippet illustrates how to create a DataFrame from two Series, `height_series` and `weight_series`, by constructing a dictionary where the keys are the desired column names and assigning the Series as the values.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using the <code>pd.concat()</code> Function</h2>


<p class="has-global-color-8-background-color has-background">The concat function in pandas can be used to concatenate multiple Series objects into a DataFrame along a particular axis (by default, axis=0, which means row-wise concatenation). If you have multiple Series and want to create a DataFrame where each Series forms a row, you would use <code>pd.concat()</code> with <code>axis=1</code>.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Create two series
series_a = pd.Series([101, 102, 103])
series_b = pd.Series([201, 202, 203])

# Concatenate series into a dataframe
result_df = pd.concat([series_a, series_b], axis=1)
</pre>


<p>Output:</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="">     0    1
0  101  201
1  102  202
2  103  203
</pre>


<p>The code shows how to combine two Series into a single DataFrame by concatenating them column-wise. This results in each Series becoming its own column within the new DataFrame. Note that the column names need to be specified separately if needed.</p>



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


<ul class="wp-block-list">
    
<li><b>Method 1:</b> DataFrame Constructor. Straightforward and preserves Series name. However, customization is limited to setting column names.</li>

    
<li><b>Method 2:</b> Series.to_frame(). A very concise way to create a DataFrame from a Series. Limited if needing to combine with other data structures.</li>

    
<li><b>Method 3:</b> Assigning Series to DataFrame Columns. Excellent for building up DataFrames incrementally. Adds verbosity if used only to convert a single Series.</li>

    
<li><b>Method 4:</b> Dictionary of Series. Ideal for creating DataFrames with multiple columns from series, but can become unwieldy with a large number of series.</li>

    
<li><b>Bonus Method 5:</b> pd.concat(). Versatile for multiple Series, especially if a transpose-like operation is desired. But may require additional configuration for axes and labels.</li>

</ul>

<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-a-series/">5 Best Ways to Create a Pandas DataFrame from a Series</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 Create a DataFrame from a List of Dicts in Pandas</title>
		<link>https://blog.finxter.com/5-best-ways-to-create-a-dataframe-from-a-list-of-dicts-in-pandas/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 16 Feb 2024 10:55:09 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1655074</guid>

					<description><![CDATA[<p>💡 Problem Formulation: Developers often manipulate data in the form of dictionaries and need a robust method to convert it to Pandas DataFrames for more complex analysis. Imagine you have a list of Python dictionaries, where each dictionary represents a data point with keys as column names and values as data entries. The goal is ... <a title="5 Best Ways to Create a DataFrame from a List of Dicts in Pandas" class="read-more" href="https://blog.finxter.com/5-best-ways-to-create-a-dataframe-from-a-list-of-dicts-in-pandas/" aria-label="Read more about 5 Best Ways to Create a DataFrame from a List of Dicts in Pandas">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-dataframe-from-a-list-of-dicts-in-pandas/">5 Best Ways to Create a DataFrame from a List of Dicts in Pandas</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"><b><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;" /> Problem Formulation:</b> Developers often manipulate data in the form of dictionaries and need a robust method to convert it to Pandas DataFrames for more complex analysis. Imagine you have a list of Python dictionaries, where each dictionary represents a data point with keys as column names and values as data entries. The goal is to convert this list into a structured Pandas DataFrame, which affords the rich functionalities for data manipulation that Pandas provides.</p>



<h2 class="wp-block-heading">Method 1: Using DataFrame Constructor</h2>


<p class="has-global-color-8-background-color has-background">Pandas provides a direct DataFrame constructor that is equipped to handle a list of dictionaries, instantly turning it into a DataFrame. Each dictionary in the list represents a row, and DataFrame construction is as straightforward as passing the list to <code>pandas.DataFrame()</code>.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Sample list of dictionaries
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]

# Creating DataFrame
df = pd.DataFrame(data)</pre>


<p>The output of this code will be:</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="">      name  age
0    Alice   25
1      Bob   30
2  Charlie   35</pre>


<p>This code snippet creates a DataFrame from a list of dictionaries where each dictionary represents a row in the DataFrame. It is an intuitive and widely-used method to convert structured data to a DataFrame.</p>



<h2 class="wp-block-heading">Method 2: Using from_records()</h2>


<p class="has-global-color-8-background-color has-background">The <code>pandas.DataFrame.from_records()</code> method is tailored for converting structured data like a list of tuples or a list of dictionaries to a DataFrame. While similar in functionality to the DataFrame constructor, <code>from_records()</code> provides additional flexibility such as specifying which columns to include.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Sample list of dictionaries
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]

# Creating DataFrame
df = pd.DataFrame.from_records(data)</pre>


<p>The output of this code will be:</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="">      name  age
0    Alice   25
1      Bob   30
2  Charlie   35</pre>


<p>The <code>from_records()</code> method provides a clean and explicit way to create DataFrames from structured data records. It&#8217;s ideal when you want to ensure clarity within your code regarding data origins.</p>



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


<p class="has-global-color-8-background-color has-background">For JSON-like nested structures, <code>pandas.json_normalize()</code> is a powerful tool that can flatten the data and create a DataFrame. It&#8217;s particularly useful when dealing with nested dictionaries or when you need to select certain parts of the dictionary to be expanded into columns.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Sample list of nested dictionaries
data = [{'name': 'Alice', 'age': 25, 'contacts': {'email': 'alice@example.com'}},
        {'name': 'Bob', 'age': 30, 'contacts': {'email': 'bob@example.com'}},
        {'name': 'Charlie', 'age': 35, 'contacts': {'email': 'charlie@example.com'}}]

# Creating DataFrame with json_normalize
df = pd.json_normalize(data)</pre>


<p>The output of this code will be:</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="">      name  age          contacts.email
0    Alice   25     alice@example.com
1      Bob   30       bob@example.com
2  Charlie   35  charlie@example.com</pre>


<p>This showcases <code>json_normalize()</code>&#8216;s capability to take nested dictionary structures and neatly convert them into a flat table, where each nested key-value pair is transformed into a column in the DataFrame.</p>



<h2 class="wp-block-heading">Method 4: Using DictVectorizer from Scikit-learn</h2>


<p class="has-global-color-8-background-color has-background">When working with categorical data and intending to perform machine learning tasks, using <code>DictVectorizer</code> from Scikit-learn could be beneficial. This method converts lists of feature mappings (dicts) to vectors and is an integral part of feature extraction.</p>


<p>Here&#8217;s an 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="">from sklearn.feature_extraction import DictVectorizer
import pandas as pd

# Sample list of dictionaries
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]

# Converting to DataFrame using DictVectorizer
dv = DictVectorizer(sparse=False)
df = pd.DataFrame(dv.fit_transform(data), columns=dv.get_feature_names())</pre>


<p>The output of this code will be:</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="">    age  name=Alice  name=Bob  name=Charlie
0  25.0         1.0       0.0           0.0
1  30.0         0.0       1.0           0.0
2  35.0         0.0       0.0           1.0</pre>


<p>This method translates each unique key-value pair into a separate column, using one-hot encoding for categorical features. This readies the dataset for machine learning algorithms that expect numerical input.</p>



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


<p class="has-global-color-8-background-color has-background">For smaller datasets or inline operations, Python&#8217;s list comprehensions can be used to craft a DataFrame in a very Pythonic, albeit less direct, way. This allows for greater control over data manipulation before the DataFrame creation.</p>


<p>Here&#8217;s an 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="">import pandas as pd

# Sample list of dictionaries
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]

# Creating DataFrame using a comprehension
df = pd.DataFrame({key: [dic[key] for dic in data] for key in data[0]})</pre>


<p>The output of this code will be:</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="">      name  age
0    Alice   25
1      Bob   30
2  Charlie   35</pre>


<p>This method relies on the comprehension&#8217;s ability to iterate over the dictionaries to extract keys and values, which are then passed into the DataFrame constructor in a transposed format, resulting in a neat and familiar table structure.</p>



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



<ul class="wp-block-list">

<li><b>Method 1:</b> DataFrame Constructor. Simple and Pythonic; widely used. However, it doesn&#8217;t cater specifically to more complex or nested dictionary structures.</li>


<li><b>Method 2:</b> from_records(). Similar to the constructor, but allows for more explicit data handling. Not as direct as simply using the constructor.</li>


<li><b>Method 3:</b> json_normalize(). Best for nested dictionaries or JSON data; it can handle deep nesting. Might be overkill for simple, flat data structures.</li>


<li><b>Method 4:</b> DictVectorizer. Ideal for data that will be used in machine learning. Not suitable for general data processing where feature encoding is not required.</li>


<li><b>Method 5:</b> Comprehensions. Pythonic and allows for inline data manipulation. Not as readable, and potentially less efficient for larger data sets.</li>

</ul>

<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-dataframe-from-a-list-of-dicts-in-pandas/">5 Best Ways to Create a DataFrame from a List of Dicts in Pandas</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 Create a Pandas DataFrame from CSV</title>
		<link>https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-csv/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 16 Feb 2024 10:55:09 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1655075</guid>

					<description><![CDATA[<p>💡 Problem Formulation: When working with data in Python, one common task is to import data from a CSV file into a Pandas DataFrame. A CSV (Comma-Separated Values) file is a type of plain text file that uses specific structuring to arrange tabular data. Creating a DataFrame from a CSV file allows for more complex ... <a title="5 Best Ways to Create a Pandas DataFrame from CSV" class="read-more" href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-csv/" aria-label="Read more about 5 Best Ways to Create a Pandas DataFrame from CSV">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-csv/">5 Best Ways to Create a Pandas DataFrame from CSV</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"><b><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;" /> Problem Formulation:</b> When working with data in Python, one common task is to import data from a CSV file into a Pandas DataFrame. A CSV (Comma-Separated Values) file is a type of plain text file that uses specific structuring to arrange tabular data. Creating a DataFrame from a CSV file allows for more complex data manipulations. The input is a CSV file containing data, and the desired output is a Pandas DataFrame with the same tabular data ready for analysis.</p>



<h2 class="wp-block-heading">Method 1: Using <code>pd.read_csv()</code> Function</h2>


<p class="has-global-color-8-background-color has-background">The <code>pd.read_csv()</code> function is the most common and straightforward method to create a DataFrame from a CSV file. The function reads a CSV into a DataFrame and offers a wealth of parameters to handle different data parsing scenarios, such as custom delimiter and handling missing values.</p>


<p>Here&#8217;s an 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="">import pandas as pd

df = pd.read_csv('data.csv')
print(df.head())
</pre>


<p>Output of this code snippet:</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="">  Name  Age  Salary
0  John   28   50000
1  Jane   35   70000
2  Doe    40   60000
</pre>


<p>This example loads the CSV file <code>data.csv</code> into a DataFrame and prints the first few rows. The <code>.head()</code> method is a quick way to inspect the first few entries of the DataFrame, ensuring it&#8217;s loaded correctly.</p>



<h2 class="wp-block-heading">Method 2: Specifying Custom Delimiters</h2>


<p class="has-global-color-8-background-color has-background">CSV files may use delimiters other than commas, such as tabs or spaces. Pandas can handle various delimiters using the <code>sep</code> parameter of the <code>read_csv()</code> function.</p>


<p>Here&#8217;s an 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="">df = pd.read_csv('data.tsv', sep='\t')
print(df.head())
</pre>


<p>Output of this code snippet:</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="">  Name  Age  Salary
0  John   28   50000
1  Jane   35   70000
2  Doe    40   60000
</pre>


<p>This snippet imports data from a tab-separated values (TSV) file using <code>\t</code> as the delimiter. This allows the function to properly parse the TSV data into a DataFrame.</p>



<h2 class="wp-block-heading">Method 3: Handling Missing Values</h2>


<p class="has-global-color-8-background-color has-background">Pandas provides parameters such as <code>na_values</code> to specify additional strings to recognize as NA/NaN. This is useful for dealing with CSV files that represent missing values with custom placeholders.</p>


<p>Here&#8217;s an 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="">df = pd.read_csv('data.csv', na_values=["NA", "?"])
print(df.head())
</pre>


<p>Output of this snippet might look like this, assuming &#8220;NA&#8221; and &#8220;?&#8221; were present in the file:</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="">  Name   Age  Salary
0  John  28.0   50000
1  Jane   NaN   70000
2  Doe   40.0     NaN
</pre>


<p>This snippet demonstrates how to handle missing values by converting &#8220;NA&#8221; and &#8220;?&#8221; into NaN in the resulting DataFrame. It makes downstream data processing more consistent by standardizing the representation of missing values.</p>



<h2 class="wp-block-heading">Method 4: Skipping Rows</h2>


<p class="has-global-color-8-background-color has-background">If the CSV file includes metadata or comments that you don&#8217;t want to load, you can use the <code>skiprows</code> parameter to ignore the first few lines, or pass a list of row indices to skip specific rows.</p>


<p>Here&#8217;s an 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="">df = pd.read_csv('data_with_header.csv', skiprows=4)
print(df.head())
</pre>


<p>Output of this code snippet:</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="">  Name  Age  Salary
0  John   28   50000
1  Jane   35   70000
2  Doe    40   60000
</pre>


<p>The example shows how to create a DataFrame by skipping the first four lines of the CSV file. This is particularly useful when CSV files contain prefatory information before the actual data.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Loading a CSV and Squeezing Single Column Data into a Series</h2>


<p class="has-global-color-8-background-color has-background">When you have a CSV with only one data column and you want to load it as a Pandas Series, you can use the combination of parameters <code>usecols</code> and <code>squeeze</code>.</p>


<p>Here&#8217;s an 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="">series = pd.read_csv('single_column_data.csv', usecols=[0], squeeze=True)
print(series.head())
</pre>


<p>Output of this code snippet:</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="">0    John
1    Jane
2    Doe
Name: Name, dtype: object
</pre>


<p>This one-liner loads the first column of the CSV file into a Series object. If a DataFrame is not required because the CSV file contains a single column, this method is efficient and concise.</p>



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


<p class="has-global-color-8-background-color has-background">
<b>Method 1:</b> <code>pd.read_csv()</code>. Straightforward and versatile. Cannot handle complex parsing without additional parameters.<br>
<b>Method 2:</b> Custom Delimiters. Flexible for various file formats. Requires knowledge of the file&#8217;s structure.<br>
<b>Method 3:</b> Handling Missing Values. Efficient for cleaning data. May require additional context on what constitutes a missing value in your data.<br>
<b>Method 4:</b> Skipping Rows. Useful for messy CSV files. Can become cumbersome if too many specific rows need to be skipped.<br>
<b>Method 5:</b> Squeeze to Series. Concise for single-column data. Limited to single-column CSV files only.
</p>

<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-csv/">5 Best Ways to Create a Pandas DataFrame from CSV</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 Efficient Ways to Create a pandas DataFrame from JSON</title>
		<link>https://blog.finxter.com/5-efficient-ways-to-create-a-pandas-dataframe-from-json/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 16 Feb 2024 10:55:09 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1655076</guid>

					<description><![CDATA[<p>💡 Problem Formulation: In data analysis, it&#8217;s common practice to convert JSON data into pandas DataFrames. The conversion process can be crucial for preparing data for analysis, especially when dealing with JSON which is widely used in web APIs and config files. For instance, converting a JSON array of user records into a DataFrame for ... <a title="5 Efficient Ways to Create a pandas DataFrame from JSON" class="read-more" href="https://blog.finxter.com/5-efficient-ways-to-create-a-pandas-dataframe-from-json/" aria-label="Read more about 5 Efficient Ways to Create a pandas DataFrame from JSON">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-efficient-ways-to-create-a-pandas-dataframe-from-json/">5 Efficient Ways to Create a pandas DataFrame from JSON</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"><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;" /> Problem Formulation:</strong> In data analysis, it&#8217;s common practice to convert JSON data into pandas DataFrames. The conversion process can be crucial for preparing data for analysis, especially when dealing with JSON which is widely used in web APIs and config files. For instance, converting a JSON array of user records into a DataFrame for analysis. The goal is to demonstrate how to perform this conversion efficiently using pandas.</p>



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


<p class="has-global-color-8-background-color has-background">For loading JSON data directly from a file or a JSON string, pandas offer the <code>pd.read_json()</code> function. It parses the JSON input into a DataFrame, recognizes multiple orientations, and interprets nested JSON as objects within the DataFrame.</p>


<p>Here&#8217;s an 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="">import pandas as pd

json_string = '{"name": "John", "age": 30, "city": "New York"}'
df = pd.read_json(json_string, orient='index')

print(df)
</pre>


<p>Output:</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="">             0
name      John
age         30
city  New York
</pre>


<p>This code demonstrates the creation of a DataFrame by parsing a simple JSON string. The <code>orient='index'</code> parameter tells pandas to use dictionary keys as row labels.</p>



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


<p class="has-global-color-8-background-color has-background">To convert a nested JSON object into a flat table, pandas provides the <code>json_normalize()</code> function. It is particularly useful for JSON objects with nested arrays or dictionaries.</p>


<p>Here&#8217;s an 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="">from pandas import json_normalize

nested_json = {
    "name": "Jane",
    "location": {
        "city": "Los Angeles",
        "state": "CA"
    }
}
df_normalized = json_normalize(nested_json)

print(df_normalized)
</pre>


<p>Output:</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="">   name location.city location.state
0  Jane   Los Angeles             CA
</pre>


<p>This snippet uses <code>json_normalize()</code> to convert nested JSON into a DataFrame, creating a flat structure where the keys become column names.</p>



<h2 class="wp-block-heading">Method 3: From a List of JSON objects</h2>


<p class="has-global-color-8-background-color has-background">Casting a list of JSON objects directly into a DataFrame is straightforward if each list item corresponds to a row in the DataFrame.</p>


<p>Here&#8217;s an 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="">import pandas as pd

json_list = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 35}
]
df_from_list = pd.DataFrame(json_list)

print(df_from_list)
</pre>


<p>Output:</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="">      name  age
0    Alice   25
1      Bob   30
2  Charlie   35
</pre>


<p>This code constructs a DataFrame from a list of dictionaries, with each dictionary representing a JSON object and each key-value pair defining a column and a data point respectively.</p>



<h2 class="wp-block-heading">Method 4: Using <code>pd.io.json.loads()</code> and <code>pd.DataFrame()</code></h2>


<p class="has-global-color-8-background-color has-background">If your JSON data is received as a string, you can first parse it using <code>pd.io.json.loads()</code> and then create a DataFrame with <code>pd.DataFrame()</code>.</p>


<p>Here&#8217;s an 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="">import pandas as pd
from pandas.io.json import json_normalize

json_str = '[{"name": "Dave", "age": 40}, {"name": "Eve", "age": 45}]'
json_data = json.loads(json_str)
df_from_json_str = pd.DataFrame(json_data)

print(df_from_json_str)
</pre>


<p>Output:</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="">   name  age
0  Dave   40
1   Eve   45
</pre>


<p>This method involves converting the JSON string into a list of dictionary objects, which <code>pd.DataFrame()</code> then readily converts into a DataFrame.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using List Comprehension with <code>pd.DataFrame()</code></h2>


<p class="has-global-color-8-background-color has-background">If you are dealing with a relatively simple JSON structure and prefer a one-liner, you can use list comprehension combined with <code>pd.DataFrame()</code> to build your DataFrame.</p>


<p>Here&#8217;s an 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="">import pandas as pd

df_one_liner = pd.DataFrame([{"name": "Frank", "age": 50}, {"name": "Grace", "age": 45}])

print(df_one_liner)
</pre>


<p>Output:</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="">    name  age
0  Frank   50
1  Grace   45
</pre>


<p>This compact approach directly passes the JSON array into <code>pd.DataFrame()</code>, immediately creating the DataFrame without additional steps.</p>



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


<ul class="wp-block-list">
    
<li><strong>Method 1:</strong> Using <code>pd.read_json()</code>. Best for JSON strings or file inputs. Not ideal for highly nested JSON.</li>

    
<li><strong>Method 2:</strong> Using <code>json_normalize()</code>. Ideal for nested JSON structures. May require additional parameters for complex data.</li>

    
<li><strong>Method 3:</strong> From a list of JSON objects. Streamlined for lists of dictionaries. Limited to non-nested JSON.</li>

    
<li><strong>Method 4:</strong> Using <code>pd.io.json.loads()</code> and <code>pd.DataFrame()</code>. Versatile for JSON strings. Involves two-step conversion.</li>

    
<li><strong>Bonus Method 5:</strong> Using list comprehension with <code>pd.DataFrame()</code>. Quick one-liner for simple JSON arrays. May not be suitable for complex data transformations.</li>

</ul>


<p>The post <a href="https://blog.finxter.com/5-efficient-ways-to-create-a-pandas-dataframe-from-json/">5 Efficient Ways to Create a pandas DataFrame from JSON</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 Create a Pandas DataFrame from an Array</title>
		<link>https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-an-array/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 16 Feb 2024 10:55:09 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1655077</guid>

					<description><![CDATA[<p>💡 Problem Formulation: Converting an array into a DataFrame is a common task in data analysis. This involves taking input like a NumPy array or a list of lists and transforming it into a structured DataFrame using the Pandas library. The expected output is a Pandas DataFrame with rows and columns that reflect the structure ... <a title="5 Best Ways to Create a Pandas DataFrame from an Array" class="read-more" href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-an-array/" aria-label="Read more about 5 Best Ways to Create a Pandas DataFrame from an Array">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-an-array/">5 Best Ways to Create a Pandas DataFrame from an Array</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"><b><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;" /> Problem Formulation:</b> Converting an array into a DataFrame is a common task in data analysis. This involves taking input like a NumPy array or a list of lists and transforming it into a structured DataFrame using the Pandas library. The expected output is a Pandas DataFrame with rows and columns that reflect the structure and data of the original array.</p>



<h2 class="wp-block-heading">Method 1: Using DataFrame Constructor</h2>


<p class="has-global-color-8-background-color has-background">The Pandas <code>DataFrame</code> constructor is the most straightforward method to create a DataFrame from an array. You simply pass the array directly into the constructor, and optionally specify column names if required. The result is a neatly formatted DataFrame that presents the array in a tabular fashion.</p>


<p>Here&#8217;s an 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="">import pandas as pd
import numpy as np

data_array = np.array([[1, 2, 3], [4, 5, 6]])
df = pd.DataFrame(data_array, columns=['A', 'B', 'C'])

print(df)</pre>


<p>The output of this code snippet:</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="">   A  B  C
0  1  2  3
1  4  5  6</pre>


<p>This code imports Pandas and NumPy, creates a 2-dimensional NumPy array, and then passes this array to the Pandas DataFrame constructor, resulting in a DataFrame with three columns labeled &#8216;A&#8217;, &#8216;B&#8217;, and &#8216;C&#8217;.</p>



<h2 class="wp-block-heading">Method 2: DataFrame from List of Lists</h2>


<p class="has-global-color-8-background-color has-background">When dealing with a plain Python list of lists, you can also use the DataFrame constructor by simply passing the list directly. This is useful when you&#8217;re not working with NumPy and your data is already in a list format.</p>


<p>Here&#8217;s an 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="">import pandas as pd

data_list = [[7, 8, 9], [10, 11, 12]]
df = pd.DataFrame(data_list, columns=['X', 'Y', 'Z'])

print(df)</pre>


<p>The output of this code snippet:</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="">    X   Y   Z
0   7   8   9
1  10  11  12</pre>


<p>This snippet creates a DataFrame from a list of lists by passing the list object to the DataFrame constructor. This results in a DataFrame with the same number of columns as there are elements in the sublists, and as many rows as there are sublists.</p>



<h2 class="wp-block-heading">Method 3: DataFrame with Custom Indices</h2>


<p class="has-global-color-8-background-color has-background">Adding indices is an important feature when you want to identify rows with specific labels rather than default integer-based indices. By using the <code>index</code> argument in the DataFrame constructor, you can assign a custom index to your data.</p>


<p>Here&#8217;s an 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="">import pandas as pd

array = [[13, 14], [15, 16]]
df = pd.DataFrame(array, columns=['Column1', 'Column2'], index=['Row1', 'Row2'])

print(df)</pre>


<p>The output of this code snippet:</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="">      Column1  Column2
Row1       13       14
Row2       15       16</pre>


<p>This code creates a DataFrame with custom row indices &#8216;Row1&#8217; and &#8216;Row2&#8217;. The DataFrame is populated with the data from the 2-dimensional array along with the specified column names.</p>



<h2 class="wp-block-heading">Method 4: Using <code>pd.DataFrame.from_records()</code></h2>


<p class="has-global-color-8-background-color has-background">The <code>from_records()</code> method is particularly useful when dealing with a list of tuples or arrays. It assumes each tuple or array in the list is a record, and the resulting DataFrame uses these records as rows.</p>


<p>Here&#8217;s an 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="">import pandas as pd

records = [(20, 'red'), (21, 'blue')]
df = pd.DataFrame.from_records(records, columns=['Number', 'Color'])

print(df)</pre>


<p>The output of this code snippet:</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="">   Number Color
0      20   red
1      21  blue</pre>


<p>This example takes a list of tuples, with each tuple representing a record, and uses <code>pd.DataFrame.from_records()</code> to create a DataFrame with columns &#8216;Number&#8217; and &#8216;Color&#8217;.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using <code>pd.DataFrame()</code> with Zip</h2>


<p class="has-global-color-8-background-color has-background">For a quick and efficient one-liner, you can use <code>zip</code> to merge multiple lists into a DataFrame. This method is best when your data is already separated into individual column lists.</p>


<p>Here&#8217;s an 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="">import pandas as pd

col1 = [22, 23]
col2 = ['green', 'yellow']
df = pd.DataFrame(list(zip(col1, col2)), columns=['Number', 'Color'])

print(df)</pre>


<p>The output of this code snippet:</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="">   Number   Color
0      22   green
1      23  yellow</pre>


<p>This snippet zips two lists together into a list of tuples and instantly converts it into a DataFrame with the specified column names, all in a single line of code.</p>



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


<ul class="wp-block-list">

<li><b>Method 1:</b> DataFrame Constructor. Simple and straightforward. Ideally used with NumPy arrays.</li>


<li><b>Method 2:</b> DataFrame from List of Lists. Perfect for Python lists, maintaining simplicity without needing NumPy.</li>


<li><b>Method 3:</b> DataFrame with Custom Indices. Adds the ability to label rows with custom indices. Useful for labeled data.</li>


<li><b>Method 4:</b> Using <code>pd.DataFrame.from_records()</code>. Great for lists of tuples or records. Each tuple naturally becomes a row.</li>


<li><b>Bonus Method 5:</b> Using <code>pd.DataFrame()</code> with Zip. Efficient one-liner for combining multiple lists into a DataFrame.</li>

</ul>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-create-a-pandas-dataframe-from-an-array/">5 Best Ways to Create a Pandas DataFrame from an Array</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-27 10:20:27 by W3 Total Cache
-->