{"id":134023,"date":"2023-08-06T09:10:11","date_gmt":"2023-08-06T09:10:11","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1550560"},"modified":"2023-08-06T09:10:11","modified_gmt":"2023-08-06T09:10:11","slug":"5-effective-methods-to-sort-a-list-of-string-numbers-numerically-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/08\/06\/5-effective-methods-to-sort-a-list-of-string-numbers-numerically-in-python\/","title":{"rendered":"5 Effective Methods to Sort a List of String Numbers Numerically in Python"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1550560&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;5 Effective Methods to Sort a List of String Numbers Numerically in Python&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<h2 class=\"wp-block-heading\">Problem Formulation<\/h2>\n<p>Sorting a list of string numbers numerically in Python can lead to unexpected issues. <\/p>\n<p>For <a rel=\"noreferrer noopener\" href=\"https:\/\/stackoverflow.com\/questions\/3426108\/how-to-sort-a-list-of-strings-numerically\" data-type=\"URL\" data-id=\"https:\/\/stackoverflow.com\/questions\/3426108\/how-to-sort-a-list-of-strings-numerically\" target=\"_blank\">example<\/a>, using the naive approach to sort the list <code>lst = [\"1\", \"10\", \"3\", \"22\", \"23\", \"4\", \"2\", \"200\"]<\/code> using <code>lst.sort()<\/code> will result in the incorrect order as it sorts the list of strings lexicographically, not numerically.<\/p>\n<p>In this short article, my goal is to present the <strong>five best methods to correctly sort this list numerically<\/strong>. My recommended approach is the fifth one, see below. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f447.png\" alt=\"\ud83d\udc47\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2 class=\"wp-block-heading\">Method 1: Convert Strings to Integers and Sort<\/h2>\n<p>This method involves converting each string in the list to an integer and then sorting them. It&#8217;s a direct and simple approach to ensure numerical ordering.<\/p>\n<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 = [int(x) for x in lst]\nlst.sort()\n<\/pre>\n<p><strong>Output<\/strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\" rel=\"noreferrer noopener\">Python List Comprehension<\/a><\/p>\n<h2 class=\"wp-block-heading\">Method 2: Using the <code>key<\/code> Parameter with sort()<\/h2>\n<p>This method uses the <code>key<\/code> parameter with the <code>int<\/code> function to sort the strings as integers. It allows for numerical comparison without altering the original strings.<\/p>\n<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.sort(key=int)\n<\/pre>\n<p><strong>Output<\/strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/sort-a-list-string-tuple-in-python-sort-sorted\/\" data-type=\"post\" data-id=\"1550507\" target=\"_blank\" rel=\"noreferrer noopener\">Python <code>list.sort()<\/code> with key parameter<\/a><\/p>\n<h2 class=\"wp-block-heading\">Method 3: Using the natsort Module<\/h2>\n<p>The <code>natsort<\/code> module provides a natural sorting algorithm, useful for sorting strings that represent numbers. This method can handle more complex string sorting scenarios.<\/p>\n<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 natsort import natsorted\nlst = natsorted(lst)\n<\/pre>\n<p><strong>Output<\/strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']<\/code><\/p>\n<h2 class=\"wp-block-heading\">Method 4: Using Regular Expressions<\/h2>\n<p>Using regular expressions, this method can sort strings containing both letters and numbers. It converts the numeric parts into floats for comparison, handling mixed content.<\/p>\n<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 re def sort_human(l): convert = lambda text: float(text) if text.isdigit() else text alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\\.?[0-9]*)', key)] l.sort(key=alphanum) return l lst = sort_human(lst)\n<\/pre>\n<p><strong>Output<\/strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-regex\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Regular Expression Superpower<\/a><\/p>\n<h2 class=\"wp-block-heading\">Method 5: Using sorted() with key Parameter (Recommended)<\/h2>\n<p>This method combines the simplicity of using the <code>key<\/code> parameter with the benefit of creating a new sorted list, leaving the original untouched. It\u2019s concise and effective.<\/p>\n<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 = sorted(lst, key=int)\n<\/pre>\n<p><strong>Output<\/strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-sorted-function\/\" data-type=\"post\" data-id=\"18072\" target=\"_blank\" rel=\"noreferrer noopener\">Python <code>sorted()<\/code> function<\/a><\/p>\n<h2 class=\"wp-block-heading\">Summary &#8211; When to Use Which<\/h2>\n<ul class=\"has-global-color-8-background-color has-background\">\n<li><strong>Method 1<\/strong>: Converts strings to integers, then sorts. Simple but alters the original list.<\/li>\n<li><strong>Method 2<\/strong>: Uses the <code>key<\/code> parameter with <code>int<\/code> for sorting. Preserves the original strings.<\/li>\n<li><strong>Method 3<\/strong>: Utilizes the <code>natsort<\/code> module. Handles complex scenarios.<\/li>\n<li><strong>Method 4<\/strong>: Employs regular expressions for sorting alphanumeric strings.<\/li>\n<li><strong>Method 5 (Recommended)<\/strong>: Combines the simplicity of using <code>key<\/code> with <code>sorted()<\/code>. Preserves the original list and offers concise code.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<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>\n<\/div>\n<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>\n<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>\n<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>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<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>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<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>\n<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>\n<\/ul>\n<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>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation Sorting a list of string numbers numerically in Python can lead to unexpected issues. For example, using the naive approach to sort the list lst = [&#8220;1&#8221;, &#8220;10&#8221;, &#8220;3&#8221;, &#8220;22&#8221;, &#8220;23&#8221;, &#8220;4&#8221;, &#8220;2&#8221;, &#8220;200&#8221;] using lst.sort() will result in the incorrect order as it sorts the list of strings [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-134023","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134023","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=134023"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134023\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=134023"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=134023"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=134023"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}