Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Sort a List, String, Tuple in Python (sort, sorted)

#1
[Tut] Sort a List, String, Tuple in Python (sort, sorted)

<div>
<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;1550507&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;Sort a List, String, Tuple in Python (sort, sorted)&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;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<h2 class="wp-block-heading">Basics of Sorting in Python</h2>
<p>In Python, sorting data structures like lists, strings, and tuples can be achieved using built-in functions like <code><a href="https://blog.finxter.com/python-list-sort/" data-type="post" data-id="7176" target="_blank" rel="noreferrer noopener">sort()</a></code> and <code><a href="https://blog.finxter.com/python-sorted-function/" data-type="post" data-id="18072" target="_blank" rel="noreferrer noopener">sorted()</a></code>. These functions enable you to arrange the data in ascending or descending order. This section will provide an overview of how to use these functions.</p>
<p class="has-global-color-8-background-color has-background">The <code>sorted()</code> function is primarily used when you want to create a new sorted list from an <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterable</a>, without modifying the original data. This function can be used with a variety of data types, such as lists, strings, and tuples. </p>
<p>Here’s an example of <a href="https://blog.finxter.com/how-to-sort-and-return-a-python-list-in-one-line/" data-type="post" data-id="12565" target="_blank" rel="noreferrer noopener">sorting a list of integers</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 8, 2, 3, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]
</pre>
<p>To sort a string or tuple, you can simply pass it to the <code>sorted()</code> function as well:</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="">text = "python"
sorted_text = sorted(text)
print(sorted_text) # Output: ['h', 'n', 'o', 'p', 't', 'y']
</pre>
<p>For <strong>descending order</strong> sorting, use the <code>reverse=True</code> argument with the <code>sorted()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 8, 2, 3, 1]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [8, 5, 3, 2, 1]
</pre>
<p class="has-global-color-8-background-color has-background">On the other hand, the <code>sort()</code> method is used when you want to modify the original list in-place. One key point to note is that the <code>sort()</code> method can only be called on lists and not on strings or tuples. </p>
<p>To sort a list using the <code>sort()</code> method, simply call this method on the <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list object</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="">numbers = [5, 8, 2, 3, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 5, 8]
</pre>
<p>For <strong>descending order</strong> sorting using the <code>sort()</code> method, pass the <code>reverse=True</code> argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 8, 2, 3, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]
</pre>
<p>Using the <code>sorted()</code> function and the <code>sort()</code> method, you can easily sort various data structures in Python, such as lists, strings, and tuples, in ascending or descending order.</p>
<p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank" rel="noreferrer noopener">Python List <code>sort()</code> – The Ultimate Guide</a></p>
<h2 class="wp-block-heading">Sorting Lists</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="564" height="849" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-48.png" alt="" class="wp-image-1550514" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-48.png 564w, https://blog.finxter.com/wp-content/uplo...99x300.png 199w" sizes="(max-width: 564px) 100vw, 564px" /></figure>
</div>
<p>In Python, sorting a list is a common operation that can be performed using either the <code>sort()</code> method or the <code>sorted()</code> function. Both these approaches can sort a list in ascending or descending order.</p>
<h3 class="wp-block-heading">Using .sort() Method</h3>
<p class="has-global-color-8-background-color has-background">The <code>sort()</code> method is a built-in method of the list object in Python. It sorts the elements of the list in-place, meaning it modifies the original list without creating a new one. By default, the <code>sort()</code> method sorts the list in ascending order.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/sort-a-list-string-tuple-in-python-sort-sorted/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaTccgHTGzo8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p>Here’s an example of how to use the <code>sort()</code> method to sort a list of 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="">numbers = [5, 2, 8, 1, 4]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 5, 8]
</pre>
<p>To sort the list in descending order, you can pass the <code>reverse=True</code> argument to the <code>sort()</code> method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 2, 8, 1, 4]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 4, 2, 1]
</pre>
<h3 class="wp-block-heading">Sorting Lists with sorted() Function</h3>
<p class="has-global-color-8-background-color has-background">The <code>sorted()</code> function is another way of sorting a list in Python. Unlike the <code>sort()</code> method, the <code>sorted()</code> function returns a new sorted list without modifying the original one.</p>
<p>Here’s an example showing how to use the <code>sorted()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 4, 5, 8]
</pre>
<p>Similar to the <code>sort()</code> method, you can sort a list in descending order using the <code>reverse=True</code> argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [8, 5, 4, 2, 1]
</pre>
<p>Both the <code>sort()</code> method and <code>sorted()</code> function allow for sorting lists as per specified sorting criteria. Use them as appropriate depending on whether you want to modify the original list or get a new sorted list.</p>
<p>Check out my video on the <code>sorted()</code> function: <img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/sort-a-list-string-tuple-in-python-sort-sorted/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaGfYP9WhUsc%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-sorted-function/" data-type="URL" data-id="https://blog.finxter.com/python-sorted-function/" target="_blank" rel="noreferrer noopener">Python <code>sorted()</code> Function</a></p>
<h2 class="wp-block-heading">Sorting Tuples</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="479" height="844" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-49.png" alt="" class="wp-image-1550515" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-49.png 479w, https://blog.finxter.com/wp-content/uplo...70x300.png 170w" sizes="(max-width: 479px) 100vw, 479px" /></figure>
</div>
<p>Tuples are <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">immutable</a> data structures in Python, similar to lists, but they are enclosed within parentheses and cannot be modified once created. Sorting tuples can be achieved using the built-in <code>sorted()</code> function.</p>
<h3 class="wp-block-heading">Ascending and Descending Order</h3>
<p>To sort a tuple or a list of tuples in <strong>ascending order</strong>, simply pass the tuple to the <code>sorted()</code> function. </p>
<p>Here’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="">my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 4, 5]
</pre>
<p>For <strong>descending order</strong>, use the optional <code>reverse</code> argument in the <code>sorted()</code> function. Setting it to <code>True</code> will sort the elements in descending order:</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="">my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple, reverse=True)
print(sorted_tuple) # Output: [5, 4, 3, 2, 1]
</pre>
<h3 class="wp-block-heading">Sorting Nested Tuples</h3>
<p>When sorting a list of tuples, Python sorts them by the first elements in the tuples, then the second elements, and so on. To effectively <strong>sort nested tuples</strong>, you can provide a custom sorting key using the <strong><a href="https://blog.finxter.com/daily-python-puzzle-sorting-lambda-function/" data-type="post" data-id="235" target="_blank" rel="noreferrer noopener"><code>key</code> argument</a></strong> in the <code>sorted()</code> function.</p>
<p>Here’s an example of sorting a <a href="https://blog.finxter.com/how-to-sort-a-list-of-tuples-most-pythonic-way/" data-type="post" data-id="10409" target="_blank" rel="noreferrer noopener">list of tuples</a> in ascending order by the second element in each tuple:</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="">my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [(3, 1), (1, 4), (2, 5)]
</pre>
<p>Alternatively, to sort in descending order, simply set the <code>reverse</code> argument to <code>True</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="">my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1], reverse=True)
print(sorted_list) # Output: [(2, 5), (1, 4), (3, 1)]
</pre>
<p>As shown, you can manipulate the <code>sorted()</code> function through its arguments to sort tuples and lists of tuples with ease. Remember, tuples are <strong>immutable</strong>, and the <code>sorted()</code> function returns a new sorted list rather than modifying the original tuple.</p>
<h2 class="wp-block-heading">Sorting Strings</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="566" height="844" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-50.png" alt="" class="wp-image-1550516" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-50.png 566w, https://blog.finxter.com/wp-content/uplo...01x300.png 201w" sizes="(max-width: 566px) 100vw, 566px" /></figure>
</div>
<p>In Python, sorting strings can be done using the <code>sorted()</code> function. This function is versatile and can be used to sort strings (<code>str</code>) in ascending (<em>alphabetical</em>) or descending (<em>reverse alphabetical</em>) order. </p>
<p>In this section, we’ll explore <strong><em>sorting individual characters in a string and sorting a list of words alphabetically</em></strong>.</p>
<h3 class="wp-block-heading">Sorting Characters</h3>
<p>To sort the characters of a string, you can pass the string to the <code>sorted()</code> function, which will return a list of characters in alphabetical order. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "python"
sorted_chars = sorted(text)
print(sorted_chars)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['h', 'n', 'o', 'p', 't', 'y']
</pre>
<p>If you want to obtain the sorted string instead of the list of characters, you can use the <code><a href="https://blog.finxter.com/python-string-join/" data-type="post" data-id="26062">join()</a></code> function to concatenate them:</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="">sorted_string = ''.join(sorted_chars)
print(sorted_string)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hnopty
</pre>
<p>For sorting the characters in descending order, set the optional <code>reverse</code> parameter to <code>True</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="">sorted_chars_desc = sorted(text, reverse=True)
print(sorted_chars_desc)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['y', 't', 'p', 'o', 'n', 'h']
</pre>
<h3 class="wp-block-heading">Sorting Words Alphabetically</h3>
<p>When you have a list of words and want to sort them alphabetically, the <code>sorted()</code> function can be applied directly 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="">words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words)
print(sorted_words)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['apple', 'banana', 'kiwi', 'orange']
</pre>
<p>To sort the words in reverse alphabetical order, use the <code>reverse</code> parameter again:</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="">sorted_words_desc = sorted(words, reverse=True)
print(sorted_words_desc)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['orange', 'kiwi', 'banana', 'apple']
</pre>
</p>
<h2 class="wp-block-heading">Using Key Parameter</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2023/08/key-scaled-1.jpg" alt="" class="wp-image-1550513" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/key-scaled-1.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption"><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Image Source</strong>: <a href="https://blog.finxter.com/daily-python-puzzle-sorting-lambda-function/" data-type="URL" data-id="https://blog.finxter.com/daily-python-puzzle-sorting-lambda-function/" target="_blank" rel="noreferrer noopener">Finxter Blog</a></figcaption></figure>
</div>
<p>The <code>key</code> parameter in Python’s <code>sort()</code> and <code>sorted()</code> functions allows you to customize the sorting process by specifying a callable to be applied to each element of the list or iterable.</p>
<h3 class="wp-block-heading">Sorting with Lambda</h3>
<p>Using <a href="https://blog.finxter.com/daily-python-puzzle-sorting-lambda-function/" data-type="post" data-id="235" target="_blank" rel="noreferrer noopener">lambda functions as the <code>key</code> argument</a> is a concise way to sort complex data structures. For example, if you have a list of tuples representing names and ages, you can sort by age using a lambda function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=lambda x: x[1])
print(sorted_names_ages)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[('Bob', 25), ('Alice', 30), ('Charlie', 35)]
</pre>
<h3 class="wp-block-heading">Using itemgetter from operator Module</h3>
<p>An alternative to using lambda functions is the <code><a href="https://blog.finxter.com/how-to-sort-a-list-of-tuples-by-second-value/" data-type="post" data-id="298030" target="_blank" rel="noreferrer noopener">itemgetter()</a></code> function from the <code>operator</code> module. The <code>itemgetter()</code> function can be used as the <code>key</code> parameter to sort by a specific index in complex data structures:</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 operator import itemgetter names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=itemgetter(1))
print(sorted_names_ages)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[('Bob', 25), ('Alice', 30), ('Charlie', 35)]
</pre>
<h3 class="wp-block-heading">Sorting with Custom Functions</h3>
<p>You can also create custom functions to be used as the <code>key</code> parameter. For example, to sort strings based on the number of vowels:</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 count_vowels(s): return sum(s.count(vowel) for vowel in 'aeiouAEIOU') words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=count_vowels)
print(sorted_words)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['apple', 'cherry', 'banana']
</pre>
<h3 class="wp-block-heading">Sorting Based on Absolute Value</h3>
<p>To sort a list of integers based on their absolute values, you can use the built-in <code><a href="https://blog.finxter.com/python-abs/" data-type="post" data-id="17541" target="_blank" rel="noreferrer noopener">abs()</a></code> function as the <code>key</code> parameter:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [5, -3, 1, -8, -7]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[1, -3, 5, -7, -8]
</pre>
<h3 class="wp-block-heading">Sorting with cmp_to_key from functools</h3>
<p>In some cases, you might need to sort based on a custom comparison function. The <code>cmp_to_key()</code> function from the <code>functools</code> module can be used to achieve this. For instance, you could create a custom comparison function to sort strings based on their lengths:</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 functools import cmp_to_key def custom_cmp(a, b): return len(a) - len(b) words = ['cat', 'bird', 'fish', 'ant']
sorted_words = sorted(words, key=cmp_to_key(custom_cmp))
print(sorted_words)
</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['cat', 'ant', 'bird', 'fish']
</pre>
</p>
<h2 class="wp-block-heading">Sorting with Reverse Parameter</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="988" height="652" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-52.png" alt="" class="wp-image-1550518" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-52.png 988w, https://blog.finxter.com/wp-content/uplo...00x198.png 300w, https://blog.finxter.com/wp-content/uplo...68x507.png 768w" sizes="(max-width: 988px) 100vw, 988px" /></figure>
</div>
<p>In Python, you can easily sort lists, strings, and tuples using the built-in functions <code>sort()</code> and <code>sorted()</code>. One notable feature of these functions is the <code>reverse</code> parameter, which allows you to control the sorting order – either in ascending or descending order.</p>
<p>By default, the <code>sort()</code> and <code>sorted()</code> functions will sort the elements in ascending order. To sort them in descending order, you simply need to set the <code>reverse</code> parameter to <code>True</code>. Let’s explore this with some examples.</p>
<p>Suppose you have a list of numbers and you want to sort it in descending order. You can use the <code>sort()</code> method for lists:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [4, 1, 7, 3, 9]
numbers.sort(reverse=True) # sorts the list in place in descending order
print(numbers) # Output: [9, 7, 4, 3, 1]
</pre>
<p>If you have a string or a tuple and want to sort in descending order, use the <code>sorted()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "abracadabra"
sorted_text = sorted(text, reverse=True)
print(sorted_text) # Output: ['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a', 'a'] values = (4, 1, 7, 3, 9)
sorted_values = sorted(values, reverse=True)
print(sorted_values) # Output: [9, 7, 4, 3, 1]
</pre>
<p>Keep in mind that the <code>sort()</code> method works only on lists, while the <code>sorted()</code> function works on any iterable, returning a new sorted list without modifying the original iterable.</p>
<p>When it comes to sorting with custom rules, such as sorting a list of tuples based on a specific element, you can use the <code>key</code> parameter in combination with the <code>reverse</code> parameter. For example, to sort a list of tuples by the second element in descending order:</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="">data = [("apple", 5), ("banana", 3), ("orange", 7), ("grape", 2)]
sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True)
print(sorted_data) # Output: [('orange', 7), ('apple', 5), ('banana', 3), ('grape', 2)]
</pre>
<p>So the <code>reverse</code> parameter in Python’s sorting functions provides you with the flexibility to sort data in either ascending or descending order. By combining it with other parameters such as <code>key</code>, you can achieve powerful and customized sorting for a variety of data structures.</p>
<h2 class="wp-block-heading">Sorting in Locale-Specific Order</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="984" height="652" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-53.png" alt="" class="wp-image-1550519" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-53.png 984w, https://blog.finxter.com/wp-content/uplo...00x199.png 300w, https://blog.finxter.com/wp-content/uplo...68x509.png 768w" sizes="(max-width: 984px) 100vw, 984px" /></figure>
</div>
<p>Sorting lists, strings, and tuples in Python is a common task, and it often requires locale-awareness to account for language-specific rules. You can sort a list, string or tuple using the built-in <code>sorted()</code> function or the <code>sort()</code> method of a list. <strong>But to sort it in a locale-specific order, you must take into account the locale’s sorting rules and character encoding.</strong></p>
<p>We can achieve locale-specific sorting using the <code>locale</code> module in Python. First, you need to import the <code>locale</code> library and set the locale using the <code>setlocale()</code> function, which takes two arguments, the category and the locale name.</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 locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Set the locale to English (US)
</pre>
<p>Next, use the <code>locale.strxfrm()</code> function as the key for the <code>sorted()</code> function or the <code>sort()</code> method. The <code>strxfrm()</code> function transforms a string into a form suitable for locale-aware comparisons, allowing the sorting function to order the strings according to the locale’s rules.</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="">strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
</pre>
<p>The <code>sorted_strings</code> list will now be sorted according to the English (US) locale, with case-insensitive and accent-aware ordering.</p>
<p>Keep in mind that it’s essential to set the correct locale before sorting, as different locales may have different sorting rules. For example, the German locale would handle umlauts differently from English, so setting the locale to <code>de_DE.UTF-8</code> would produce a different sorting order.</p>
</p>
<h2 class="wp-block-heading">Sorting Sets</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="979" height="660" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-54.png" alt="" class="wp-image-1550520" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-54.png 979w, https://blog.finxter.com/wp-content/uplo...00x202.png 300w, https://blog.finxter.com/wp-content/uplo...68x518.png 768w" sizes="(max-width: 979px) 100vw, 979px" /></figure>
</div>
<p>In Python, sets are unordered collections of unique elements. To sort a set, we must first convert it to a list or tuple, since the <code>sorted()</code> function does not work directly on sets. The <code>sorted()</code> function returns a new sorted list from the specified iterable, which can be a list, tuple, or set.</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 locale
strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
print(sorted_strings)
# ['Zebra', 'apple', 'banana', 'éclair']</pre>
<p>In this example, we begin with a set named <code>sample_set</code> containing four integers. We then use the <code>sorted()</code> function to obtain a sorted list named <code>sorted_list_from_set</code>. The output will be:</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="">[1, 2, 4, 9]
</pre>
<p>The <code>sorted()</code> function can also accept a <code>reverse</code> parameter, which determines whether to sort the output in ascending or descending order. By default, <code>reverse</code> is set to <code>False</code>, meaning that the output will be sorted in ascending order. To sort the set in descending order, we can set <code>reverse=True</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="">sorted_list_descending = sorted(sample_set, reverse=True)
print(sorted_list_descending)
</pre>
<p>This code snippet will output the following:</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="">[9, 4, 2, 1]
</pre>
<p>It’s essential to note that sorting a set using the <code>sorted()</code> function does not modify the original set. Instead, it returns a new sorted list, leaving the original set unaltered.</p>
</p>
<h2 class="wp-block-heading">Sorting by Group and Nested Data Structures</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="980" height="648" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-55.png" alt="" class="wp-image-1550521" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-55.png 980w, https://blog.finxter.com/wp-content/uplo...00x198.png 300w, https://blog.finxter.com/wp-content/uplo...68x508.png 768w" sizes="(max-width: 980px) 100vw, 980px" /></figure>
</div>
<p>Sorting nested data structures in Python can be achieved using the built-in <code>sorted()</code> function or the <code>.sort()</code> method. You can sort a list of lists or tuples based on the value of a particular element in the inner item, making it useful for organizing data in groups.</p>
<p>To sort nested data, you can use a <code>key</code> argument along with a <code>lambda</code> function or the <code>itemgetter()</code> method from the <code>operator</code> module. This allows you to specify the criteria based on which the list will be sorted.</p>
<p>For instance, suppose you have a list of tuples representing student records, where each tuple contains the student’s name and score:</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="">students = [("Alice", 85), ("Bob", 78), ("Charlie", 91), ("Diana", 92)]
</pre>
<p>To sort the list by the students’ scores, you can use the <code>sorted()</code> function with a lambda function as the key:</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="">sorted_students = sorted(students, key=lambda student: student[1])
</pre>
<p>This will produce the following sorted 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="">[("Bob", 78), ("Alice", 85), ("Charlie", 91), ("Diana", 92)]
</pre>
<p>Alternatively, you can use the <code>itemgetter()</code> method:</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 operator import itemgetter sorted_students = sorted(students, key=itemgetter(1))
</pre>
<p>This will produce the same result as using the lambda function.</p>
<p>When sorting lists containing nested data structures, consider the following tips:</p>
<ul>
<li>Use the <code>lambda</code> function or <code>itemgetter()</code> for specifying the sorting criteria.</li>
<li>Remember that <code>sorted()</code> creates a new sorted list, while the <code>.sort()</code> method modifies the original list in-place.</li>
<li>You can add the <code>reverse=True</code> argument if you want to sort the list in descending order.</li>
</ul>
<h2 class="wp-block-heading">Handling Sorting Errors</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="986" height="566" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-56.png" alt="" class="wp-image-1550522" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-56.png 986w, https://blog.finxter.com/wp-content/uplo...00x172.png 300w, https://blog.finxter.com/wp-content/uplo...68x441.png 768w" sizes="(max-width: 986px) 100vw, 986px" /></figure>
</div>
<p>When working with sorting functions in Python, you might encounter some common errors such as <code>TypeError</code>. In this section, we’ll discuss how to handle such errors and provide solutions to avoid them while sorting lists, strings, and tuples using the <code>sort()</code> and <code>sorted()</code> functions.</p>
<p><code>TypeError</code> can occur when you’re trying to sort a list that contains elements of different data types. For example, when sorting an unordered list that contains both integers and strings, Python would raise a <code>TypeError: '&lt;' not supported between instances of 'str' and 'int'</code> as it cannot compare the two different data types. </p>
<p>Consider this 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="">mixed_list = [3, 'apple', 1, 'banana']
mixed_list.sort()
# Raises: TypeError: '&lt;' not supported between instances of 'str' and 'int'
</pre>
<p>To handle the <code>TypeError</code> in this case, you can use error handling techniques such as a <code>try-except</code> block. Alternatively, you could also preprocess the list to ensure all elements have a compatible data type before sorting. Here’s an example using a <code>try-except</code> block:</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="">mixed_list = [3, 'apple', 1, 'banana']
try: mixed_list.sort()
except TypeError: print("Sorting error occurred due to incompatible data types")
</pre>
<p>Another approach is to sort the list using a custom sorting key in the <code>sorted()</code> function that can handle mixed data types. For instance, you can convert all the elements to strings before comparison:</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="">mixed_list = [3, 'apple', 1, 'banana']
sorted_list = sorted(mixed_list, key=str)
print(sorted_list) # Output: [1, 3, 'apple', 'banana']
</pre>
<p>With these techniques, you can efficiently handle sorting errors that arise due to different data types within a list, string, or tuple when using the <code>sort()</code> and <code>sorted()</code> functions in Python.</p>
<h2 class="wp-block-heading">Sorting Algorithm Stability</h2>
<p>Stability in sorting algorithms refers to the preservation of the relative order of items with equal keys. In other words, when two elements have the same key, their original order in the list should be maintained after sorting. Python offers several sorting techniques, with the most common being <code>sort()</code> for lists and <code>sorted()</code> for strings, lists, and tuples.</p>
<p>Python’s sorting algorithms are stable, which means that equal keys will have their initial order preserved in the sorted output. For example, consider a list of tuples containing student scores and their names:</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="">students = [(90, "Alice"), (80, "Bob"), (90, "Carla"), (85, "Diana")]
</pre>
<p>Sorted by scores, the list should maintain the order of students with equal scores as in the original 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="">sorted_students = sorted(students)
# Output: [(80, 'Bob'), (85, 'Diana'), (90, 'Alice'), (90, 'Carla')]
</pre>
<p>Notice that Alice and Carla both have a score of 90 but since Alice appeared earlier in the original list, she comes before Carla in the sorted list as well.</p>
<p>To take full advantage of stability in sorting, the <code>key</code> parameter can be used with both <code>sort()</code> and <code>sorted()</code>. The <code>key</code> parameter allows you to specify a custom function or callable to be applied to each element for comparison. For instance, when sorting a list of strings, you can provide a custom function to perform a case-insensitive sort:</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="">words = ["This", "is", "a", "test", "string", "from", "Andrew"]
sorted_words = sorted(words, key=str.lower)
# Output: ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
</pre>
</p>
<h2 class="wp-block-heading">Frequently Asked Questions</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="985" height="655" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-57.png" alt="" class="wp-image-1550525" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-57.png 985w, https://blog.finxter.com/wp-content/uplo...00x199.png 300w, https://blog.finxter.com/wp-content/uplo...68x511.png 768w" sizes="(max-width: 985px) 100vw, 985px" /></figure>
</div>
<h3 class="wp-block-heading">How to sort a list of tuples in descending order in Python?</h3>
<p>To sort a list of tuples in descending order, you can use the <code>sorted()</code> function with the <code>reverse=True</code> parameter. For example, for a list of tuples <code>tuples_list</code>, you can sort them in descending order like this:</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="">sorted_tuples = sorted(tuples_list, reverse=True)
</pre>
<h3 class="wp-block-heading">What is the best way to sort a string alphabetically in Python?</h3>
<p>The best way to sort a string alphabetically in Python is to use the <code>sorted()</code> function, which returns a sorted list of characters. You can then join them using the <code>join()</code> method like this:</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="">string = "hello"
sorted_string = "".join(sorted(string))
</pre>
<h3 class="wp-block-heading">What are the differences between sort() and sorted() in Python?</h3>
<p><code>sort()</code> is a method available for lists, and it sorts the list in-place, meaning it modifies the original list. <code>sorted()</code> is a built-in function that works with any iterable, returns a new sorted list of elements, and doesn’t modify the original iterable.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Using sort()
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4] # Using sorted()
numbers = (3, 1, 4, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 3, 4]
</pre>
<h3 class="wp-block-heading">How can you sort a tuple in descending order in Python?</h3>
<p>To sort a tuple in descending order, you can use the <code>sorted()</code> function with the <code>reverse=True</code> parameter, like this:</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="">tuple_numbers = (3, 1, 4, 2)
sorted_tuple = sorted(tuple_numbers, reverse=True)
</pre>
<p>Keep in mind that this will create a new list. If you want to create a new tuple instead, you can convert the sorted list back to a tuple like this:</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="">sorted_tuple = tuple(sorted_tuple)
</pre>
<h3 class="wp-block-heading">How do you sort a string in Python without using the sort function?</h3>
<p>You can sort a string without using the <code>sort()</code> function by converting the string to a list of characters, using a list comprehension to sort the characters, and then using the <code>join()</code> method to create the sorted string:</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="">string = "hello"
sorted_list = [char for char in sorted(string)]
sorted_string = "".join(sorted_list)
</pre>
<h3 class="wp-block-heading">What is the method to sort a list of strings with numbers in Python?</h3>
<p>If you have a list of strings containing numbers and want to sort them based on the numeric value, you can use the <code>sorted()</code> function with a custom <code>key</code> parameter. For example, to sort a list of strings like <code>["5", "2", "10", "1"]</code>, you can do:</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="">strings_with_numbers = ["5", "2", "10", "1"]
sorted_strings = sorted(strings_with_numbers, key=int)
</pre>
<p>This will sort the list based on the integer values of the strings: <code>["1", "2", "5", "10"]</code>.</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 decoding="async" loading="lazy" 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/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(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 “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’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’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’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’ll also learn how to:</p>
<ul>
<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’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” 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>
<p>The post <a rel="nofollow" href="https://blog.finxter.com/sort-a-list-string-tuple-in-python-sort-sorted/">Sort a List, String, Tuple in Python (sort, sorted)</a> appeared first on <a rel="nofollow" href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
</div>


https://www.sickgaming.net/blog/2023/08/...rt-sorted/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016