{"id":164820,"date":"2019-11-27T17:47:17","date_gmt":"2019-11-27T12:17:17","guid":{"rendered":"https:\/\/www.digitalvidya.com\/blog\/?p=164820"},"modified":"2022-04-28T17:33:07","modified_gmt":"2022-04-28T12:03:07","slug":"how-to-use-sorted-and-sort-in-python","status":"publish","type":"post","link":"https:\/\/www.digitalvidya.com\/blog\/how-to-use-sorted-and-sort-in-python\/","title":{"rendered":"A Descriptive Guide on How to Use sorted() and sort() in Python"},"content":{"rendered":"<p dir=\"ltr\">Python provides two methods for organizing and customizing various types of data into different data structures. We will cover the implementation of simple ordering and sorting of data structures in Python in this article, the difference between sort) (and sorted) (and the configuration of a complicated sort order.<\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Sorting is very easy in Python as the built-in functions do all the heavy lifting. All you need to do is understand how to implement these functions and play with them to suit your sorting needs.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"using-the-sorted\"><\/span><b>Using the Sorted()<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<figure id=\"attachment_165531\" aria-describedby=\"caption-attachment-165531\" style=\"width: 533px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/Q-n-A-1024x536_e23a1f2426b4980523042d9fbfae65bf.png\" alt=\"How To Sort a List?\" class=\"wp-image-165531\" width=\"533\" height=\"279\" title=\"\"><figcaption id=\"caption-attachment-165531\" class=\"wp-caption-text\">How to sort a list? Source &#8211; afternerd<\/figcaption><\/figure>\n<h3><span class=\"ez-toc-section\" id=\"sorting-numbers\"><\/span><b>Sorting Numbers<\/b><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Sorted() is used for sorting a list in Python. Take the following example in which we have defined a list of numbers and the numbers variables is used as an argument in the sorted() function.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers = [6, 9, 3, 1]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(numbers)<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 3, 6, 9]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers<\/span>\r\n\r\n<span style=\"font-weight: 400\">[6, 9, 3, 1]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">You will get a new, sorted list as an output of this. With this example, you will be able to understand the following important characteristics of sorted():<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. You don\u2019t need to define the sorted() function. It is already built-in Python&#8217;s standard installation.<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. With the sorted(), you don\u2019t have to add any parameters or arguments. It will sort the numbers from smallest to largest, i.e., in any ascending order.<\/span><\/p>\n<p><span style=\"font-weight: 400\">3. The function does not change the original variable. The sorted() provides the list in ascending order without changing the original value.<\/span><\/p>\n<p><span style=\"font-weight: 400\">4. When you call sorted() function, it returns the ordered list. This means that you can assign a variable to the output of sorted().<\/span><\/p>\n<div class=\"cta-form\"><div class=\"content\"><div class=\"left-block\"><div class=\"section-title\">Want to Know the Path to Become a <strong> Data Science Expert?<\/strong><\/div><div class=\"desc\"><p>Download Detailed Brochure and Get Complimentary access to Live Online Demo Class with Industry Expert.<\/p>\n<\/div><div class=\"time\"> Date: August 1 (Sat) | 11 AM - 12 PM (IST)<\/div><\/div><div class=\"right-block\"><script>\nvar gform;gform||(document.addEventListener(\"gform_main_scripts_loaded\",function(){gform.scriptsLoaded=!0}),document.addEventListener(\"gform\/theme\/scripts_loaded\",function(){gform.themeScriptsLoaded=!0}),window.addEventListener(\"DOMContentLoaded\",function(){gform.domLoaded=!0}),gform={domLoaded:!1,scriptsLoaded:!1,themeScriptsLoaded:!1,isFormEditor:()=>\"function\"==typeof InitializeEditor,callIfLoaded:function(o){return!(!gform.domLoaded||!gform.scriptsLoaded||!gform.themeScriptsLoaded&&!gform.isFormEditor()||(gform.isFormEditor()&&console.warn(\"The use of gform.initializeOnLoaded() is deprecated in the form editor context and will be removed in Gravity Forms 3.1.\"),o(),0))},initializeOnLoaded:function(o){gform.callIfLoaded(o)||(document.addEventListener(\"gform_main_scripts_loaded\",()=>{gform.scriptsLoaded=!0,gform.callIfLoaded(o)}),document.addEventListener(\"gform\/theme\/scripts_loaded\",()=>{gform.themeScriptsLoaded=!0,gform.callIfLoaded(o)}),window.addEventListener(\"DOMContentLoaded\",()=>{gform.domLoaded=!0,gform.callIfLoaded(o)}))},hooks:{action:{},filter:{}},addAction:function(o,r,e,t){gform.addHook(\"action\",o,r,e,t)},addFilter:function(o,r,e,t){gform.addHook(\"filter\",o,r,e,t)},doAction:function(o){gform.doHook(\"action\",o,arguments)},applyFilters:function(o){return gform.doHook(\"filter\",o,arguments)},removeAction:function(o,r){gform.removeHook(\"action\",o,r)},removeFilter:function(o,r,e){gform.removeHook(\"filter\",o,r,e)},addHook:function(o,r,e,t,n){null==gform.hooks[o][r]&&(gform.hooks[o][r]=[]);var d=gform.hooks[o][r];null==n&&(n=r+\"_\"+d.length),gform.hooks[o][r].push({tag:n,callable:e,priority:t=null==t?10:t})},doHook:function(r,o,e){var t;if(e=Array.prototype.slice.call(e,1),null!=gform.hooks[r][o]&&((o=gform.hooks[r][o]).sort(function(o,r){return o.priority-r.priority}),o.forEach(function(o){\"function\"!=typeof(t=o.callable)&&(t=window[t]),\"action\"==r?t.apply(null,e):e[0]=t.apply(null,e)})),\"filter\"==r)return e[0]},removeHook:function(o,r,t,n){var e;null!=gform.hooks[o][r]&&(e=(e=gform.hooks[o][r]).filter(function(o,r,e){return!!(null!=n&&n!=o.tag||null!=t&&t!=o.priority)}),gform.hooks[o][r]=e)}});\n<\/script>\n\n                <div class='gf_browser_unknown gform_wrapper gravity-theme gform-theme--no-framework dv-form_wrapper' data-form-theme='gravity-theme' data-form-index='0' id='gform_wrapper_287' ><div id='gf_287' class='gform_anchor' tabindex='-1'><\/div><form method='post' enctype='multipart\/form-data' target='gform_ajax_frame_287' id='gform_287' class='dv-form' action='\/blog\/wp-json\/wp\/v2\/posts\/164820#gf_287' data-formid='287' novalidate>\n                        <div class='gform-body gform_body'><div id='gform_fields_287' class='gform_fields top_label form_sublabel_below description_below validation_below'><div id=\"field_287_28\" class=\"gfield gfield--type-text gfield_contains_required field_sublabel_below gfield--no-description field_description_below hidden_label field_validation_below gfield_visibility_visible\"  ><label class='gfield_label gform-field-label' for='input_287_28'>Name<span class=\"gfield_required\"><span class=\"gfield_required gfield_required_text\">(Required)<\/span><\/span><\/label><div class='ginput_container ginput_container_text'><input name='input_28' id='input_287_28' type='text' value='' class='large'    placeholder='Name *' aria-required=\"true\" aria-invalid=\"false\"   \/><\/div><\/div><div id=\"field_287_2\" class=\"gfield gfield--type-email gfield_contains_required field_sublabel_below gfield--no-description field_description_below hidden_label field_validation_below gfield_visibility_visible\"  ><label class='gfield_label gform-field-label' for='input_287_2'>Email<span class=\"gfield_required\"><span class=\"gfield_required gfield_required_text\">(Required)<\/span><\/span><\/label><div class='ginput_container ginput_container_email'>\n                            <input name='input_2' id='input_287_2' type='email' value='' class='large'   placeholder='Email *' aria-required=\"true\" aria-invalid=\"false\"  \/>\n                        <\/div><\/div><div id=\"field_287_3\" class=\"gfield gfield--type-phone gfield_contains_required field_sublabel_below gfield--no-description field_description_below hidden_label field_validation_below gfield_visibility_visible\"  ><label class='gfield_label gform-field-label' for='input_287_3'>Phone<span class=\"gfield_required\"><span class=\"gfield_required gfield_required_text\">(Required)<\/span><\/span><\/label><div class='ginput_container ginput_container_phone'><input name='input_3' id='input_287_3' type='tel' value='' class='large'  placeholder='Phone *' aria-required=\"true\" aria-invalid=\"false\"   \/><\/div><\/div><div id=\"field_287_34\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_34' id='input_287_34' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='fmc' \/><\/div><\/div><div id=\"field_287_9\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_9' id='input_287_9' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_10\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_10' id='input_287_10' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_11\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_11' id='input_287_11' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_12\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_12' id='input_287_12' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts\/164820' \/><\/div><\/div><div id=\"field_287_13\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_13' id='input_287_13' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_14\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_14' id='input_287_14' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_15\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_15' id='input_287_15' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_17\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_17' id='input_287_17' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_18\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_18' id='input_287_18' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_19\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_19' id='input_287_19' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_20\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_20' id='input_287_20' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='{dmo_day}' \/><\/div><\/div><div id=\"field_287_25\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_25' id='input_287_25' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='{dmo_date}' \/><\/div><\/div><div id=\"field_287_24\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_24' id='input_287_24' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='{dmo_time}' \/><\/div><\/div><div id=\"field_287_35\" class=\"gfield gfield--type-hidden gfield--width-full gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_35' id='input_287_35' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='{dmo_time}' \/><\/div><\/div><div id=\"field_287_36\" class=\"gfield gfield--type-hidden gfield--width-full gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_36' id='input_287_36' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_37\" class=\"gfield gfield--type-hidden gfield--width-full gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_37' id='input_287_37' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_22\" class=\"gfield gfield--type-hidden gform_hidden field_sublabel_below gfield--no-description field_description_below field_validation_below gfield_visibility_visible\"  ><div class='ginput_container ginput_container_text'><input name='input_22' id='input_287_22' type='hidden' class='gform_hidden'  aria-invalid=\"false\" value='' \/><\/div><\/div><div id=\"field_287_38\" class=\"gfield gfield--type-honeypot gform_validation_container field_sublabel_below gfield--has-description field_description_below field_validation_below gfield_visibility_visible\"  ><label class='gfield_label gform-field-label' for='input_287_38'>Name<\/label><div class='ginput_container'><input name='input_38' id='input_287_38' type='text' value='' autocomplete='new-password'\/><\/div><div class='gfield_description' id='gfield_description_287_38'>This field is for validation purposes and should be left unchanged.<\/div><\/div><\/div><\/div>\n        <div class='gform-footer gform_footer top_label'> <input type='submit' id='gform_submit_button_287' class='gform_button button' onclick='gform.submission.handleButtonClick(this);' data-submission-type='submit' value='Register Now'  \/> <input type='hidden' name='gform_ajax' value='form_id=287&amp;title=&amp;description=&amp;tabindex=0&amp;theme=gravity-theme&amp;styles=[]&amp;hash=0c9c234943f312d5985375593e68ff15' \/>\n            <input type='hidden' class='gform_hidden' name='gform_submission_method' data-js='gform_submission_method_287' value='iframe' \/>\n            <input type='hidden' class='gform_hidden' name='gform_theme' data-js='gform_theme_287' id='gform_theme_287' value='gravity-theme' \/>\n            <input type='hidden' class='gform_hidden' name='gform_style_settings' data-js='gform_style_settings_287' id='gform_style_settings_287' value='[]' \/>\n            <input type='hidden' class='gform_hidden' name='is_submit_287' value='1' \/>\n            <input type='hidden' class='gform_hidden' name='gform_submit' value='287' \/>\n            \n            <input type='hidden' class='gform_hidden' name='gform_unique_id' value='' \/>\n            <input type='hidden' class='gform_hidden' name='state_287' value='WyJbXSIsIjc5YTc5ZmI0NzJmZjc1YWM4NDI0ZmE2ZmFkNDQwNjAxIl0=' \/>\n            <input type='hidden' autocomplete='off' class='gform_hidden' name='gform_target_page_number_287' id='gform_target_page_number_287' value='0' \/>\n            <input type='hidden' autocomplete='off' class='gform_hidden' name='gform_source_page_number_287' id='gform_source_page_number_287' value='1' \/>\n            <input type='hidden' name='gform_field_values' value='' \/>\n            \n        <\/div>\n                        <p style=\"display: none !important;\" class=\"akismet-fields-container\" data-prefix=\"ak_\"><label>&#916;<textarea name=\"ak_hp_textarea\" cols=\"45\" rows=\"8\" maxlength=\"100\"><\/textarea><\/label><input type=\"hidden\" id=\"ak_js_1\" name=\"ak_js\" value=\"173\"\/><script>\ndocument.getElementById( \"ak_js_1\" ).setAttribute( \"value\", ( new Date() ).getTime() );\n<\/script>\n<\/p><\/form>\n                        <\/div>\n\t\t                <iframe style='display:none;width:0px;height:0px;' src='about:blank' name='gform_ajax_frame_287' id='gform_ajax_frame_287' title='This iframe contains the logic required to handle Ajax powered Gravity Forms.'><\/iframe>\n\t\t                <script>\ngform.initializeOnLoaded( function() {gformInitSpinner( 287, 'https:\/\/www.digitalvidya.com\/blog\/wp-content\/plugins\/gravityforms\/images\/spinner.svg', true );jQuery('#gform_ajax_frame_287').on('load',function(){var contents = jQuery(this).contents().find('*').html();var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;if(!is_postback){return;}var form_content = jQuery(this).contents().find('#gform_wrapper_287');var is_confirmation = jQuery(this).contents().find('#gform_confirmation_wrapper_287').length > 0;var is_redirect = contents.indexOf('gformRedirect(){') >= 0;var is_form = form_content.length > 0 && ! is_redirect && ! is_confirmation;var mt = parseInt(jQuery('html').css('margin-top'), 10) + parseInt(jQuery('body').css('margin-top'), 10) + 100;if(is_form){jQuery('#gform_wrapper_287').html(form_content.html());if(form_content.hasClass('gform_validation_error')){jQuery('#gform_wrapper_287').addClass('gform_validation_error');} else {jQuery('#gform_wrapper_287').removeClass('gform_validation_error');}setTimeout( function() { \/* delay the scroll by 50 milliseconds to fix a bug in chrome *\/ jQuery(document).scrollTop(jQuery('#gform_wrapper_287').offset().top - mt); }, 50 );if(window['gformInitDatepicker']) {gformInitDatepicker();}if(window['gformInitPriceFields']) {gformInitPriceFields();}var current_page = jQuery('#gform_source_page_number_287').val();gformInitSpinner( 287, 'https:\/\/www.digitalvidya.com\/blog\/wp-content\/plugins\/gravityforms\/images\/spinner.svg', true );jQuery(document).trigger('gform_page_loaded', [287, current_page]);window['gf_submitting_287'] = false;}else if(!is_redirect){var confirmation_content = jQuery(this).contents().find('.GF_AJAX_POSTBACK').html();if(!confirmation_content){confirmation_content = contents;}jQuery('#gform_wrapper_287').replaceWith(confirmation_content);jQuery(document).scrollTop(jQuery('#gf_287').offset().top - mt);jQuery(document).trigger('gform_confirmation_loaded', [287]);window['gf_submitting_287'] = false;wp.a11y.speak(jQuery('#gform_confirmation_message_287').text());}else{jQuery('#gform_287').append(contents);if(window['gformRedirect']) {gformRedirect();}}jQuery(document).trigger(\"gform_pre_post_render\", [{ formId: \"287\", currentPage: \"current_page\", abort: function() { this.preventDefault(); } }]);        if (event && event.defaultPrevented) {                return;        }        const gformWrapperDiv = document.getElementById( \"gform_wrapper_287\" );        if ( gformWrapperDiv ) {            const visibilitySpan = document.createElement( \"span\" );            visibilitySpan.id = \"gform_visibility_test_287\";            gformWrapperDiv.insertAdjacentElement( \"afterend\", visibilitySpan );        }        const visibilityTestDiv = document.getElementById( \"gform_visibility_test_287\" );        let postRenderFired = false;        function triggerPostRender() {            if ( postRenderFired ) {                return;            }            postRenderFired = true;            gform.core.triggerPostRenderEvents( 287, current_page );            if ( visibilityTestDiv ) {                visibilityTestDiv.parentNode.removeChild( visibilityTestDiv );            }        }        function debounce( func, wait, immediate ) {            var timeout;            return function() {                var context = this, args = arguments;                var later = function() {                    timeout = null;                    if ( !immediate ) func.apply( context, args );                };                var callNow = immediate && !timeout;                clearTimeout( timeout );                timeout = setTimeout( later, wait );                if ( callNow ) func.apply( context, args );            };        }        const debouncedTriggerPostRender = debounce( function() {            triggerPostRender();        }, 200 );        if ( visibilityTestDiv && visibilityTestDiv.offsetParent === null ) {            const observer = new MutationObserver( ( mutations ) => {                mutations.forEach( ( mutation ) => {                    if ( mutation.type === 'attributes' && visibilityTestDiv.offsetParent !== null ) {                        debouncedTriggerPostRender();                        observer.disconnect();                    }                });            });            observer.observe( document.body, {                attributes: true,                childList: false,                subtree: true,                attributeFilter: [ 'style', 'class' ],            });        } else {            triggerPostRender();        }    } );} );\n<\/script>\n<\/div><\/div><\/div>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers = [6, 9, 3, 1]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_sorted = sorted(numbers)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_sorted<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 3, 6, 9]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers<\/span>\r\n\r\n<span style=\"font-weight: 400\">[6, 9, 3, 1]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Here, you will get numbers_sorted, a new variable containing the output of sorted(). If you want to get information on sorted(), you can try calling help() function:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Python 3<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; help(sorted)<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Help on built-in function sorted in module builtins:<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">sorted(iterable, \/, *, key=None, reverse=False)<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">If you work in Python 2 and are moving on to Python 3, there are a couple of changes that you must be aware about:<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. There is no cmp parameter in sorted() function of Python 3. For introducing custom sorting logic, you have to use the key parameter. You have to use functools.cmp_to_key() for converting the cmp function of Python2 to the key function.<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. You need to pass reverse and key as keyword arguments. In Python 2, you could use them as positional arguments.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Here is an example that will help you understand the usage of sorted() n sets and tuples:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple = (6, 9, 3, 1)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set = {5, 5, 10, 1, 0}<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple_sorted = sorted(numbers_tuple)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set_sorted = sorted(numbers_set)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple_sorted<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 3, 6, 9]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set_sorted<\/span>\r\n\r\n<span style=\"font-weight: 400\">[0, 1, 5, 10]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Here you might have observed that even though you gave a tuple and a set as an input, the output was a list. This is because by definition, the sorted() function returns a new list. If you have to match the output to the input type, you have to cast the returned object to a new type. If you want to cast the output back to a set, you need to stay careful as the set is unordered by definition. <\/span><span style=\"font-weight: 400\">Here is an example that can help you do the same:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple = (6, 9, 3, 1)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set = {5, 5, 10, 1, 0}<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple_sorted = sorted(numbers_tuple)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set_sorted = sorted(numbers_set)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_tuple_sorted<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 3, 6, 9]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers_set_sorted<\/span>\r\n\r\n<span style=\"font-weight: 400\">[0, 1, 5, 10]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; tuple(numbers_tuple_sorted)<\/span>\r\n\r\n<span style=\"font-weight: 400\">(1, 3, 6, 9)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; set(numbers_set_sorted)<\/span>\r\n\r\n<span style=\"font-weight: 400\">{0, 1, 10, 5}<\/span>\r\n\r\n<span style=\"font-weight: 400\">When you cast the value of the numbers_set_sorted to a set, the result is not ordered. However, the sorted order remains in the variable, numbers_tuple_sorted.<\/span><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"sorting-strings\"><\/span><b>Sorting Strings<\/b><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<figure id=\"attachment_165532\" aria-describedby=\"caption-attachment-165532\" style=\"width: 566px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-300x188.jpeg\" alt=\"Sorting Strings\" class=\"wp-image-165532\" width=\"566\" height=\"355\" title=\"\" srcset=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-300x188.jpeg 300w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-150x94.jpeg 150w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-600x375.jpeg 600w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-220x138.jpeg 220w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-595x372.jpeg 595w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-400x250.jpeg 400w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image-480x300.jpeg 480w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/how-to-sort-a-list-of-strings-in-python-featured-image.jpeg 800w\" sizes=\"(max-width: 566px) 100vw, 566px\" \/><figcaption id=\"caption-attachment-165532\" class=\"wp-caption-text\">Sorting strings source &#8211; the renegade coder<\/figcaption><\/figure>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The str types can sort strings similarly to iterables like tuples and lists. Here is an example showing how sorted() function is used for iterating every character and ordering them in the output:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; string_number_value = '34521'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; string_value = 'I like to sort'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string_number = sorted(string_number_value)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string = sorted(string_value)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string_number<\/span>\r\n\r\n<span style=\"font-weight: 400\">['1', '2', '3', '4', '5']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string<\/span>\r\n\r\n<span style=\"font-weight: 400\">[' ', ' ', ' ', 'I', 'e', 'i', 'k', 'l', 'o', 'o', 'r', 's', 't', 't']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The sorted() function sorts the string by treating it as a list and then iterating through every character. It is important to remember that sorted() will sort every character in a sentence, including the spaces.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">To change this behavior and get the right output, you need to use the split() function. Here is an example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; string_value = 'I like to sort'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string = sorted(string_value.split())<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_string<\/span>\r\n\r\n<span style=\"font-weight: 400\">['I', 'like', 'sort', 'to']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; ' '.join(sorted_string)<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">&#8216;I like sort to&#8217;<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Here, you can see that the original sentence has been transformed into a list of words instead of treating it as a string. After this, the sorting of list takes place and the words are combined to form a string again.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"limitations-of-python-sorting\"><\/span><b>Limitations of Python Sorting<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">When you are using Python for sorting values other than integers, you will be facing some odd behaviors and limitations.<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"lists-with-non-comparable-data-types\"><\/span><strong>Lists With Non-Comparable Data Types\u00a0<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">When you are working with different data types, there might arise a case when the sorted() function cannot compare the data types. So, when you use sorted() function on a list of non-comparable data, an error will be returned. Following is an example where we try to compare an int and a none which cannot be sorted as they are incompatible:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; mixed_types = [None, 0]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(mixed_types)<\/span>\r\n\r\n<span style=\"font-weight: 400\">Traceback (most recent call last):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">TypeError: '&lt;' not supported between instances of 'int' and 'NoneType'<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The TypeError shows that the values given cannot be sorted. The program is trying to use the less than operator (&lt;) for putting the values in sorting order by checking out which value is lower. Here is another example of TypeError where you replicate the TypeError, the same error which arises when you try comparing non-comparable values:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; None &lt; 0<\/span>\r\n\r\n<span style=\"font-weight: 400\">Traceback (most recent call last):<\/span>\r\n\r\n<span style=\"font-weight: 400\">File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">TypeError: '&lt;' not supported between instances of 'NoneType' and 'int'<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The TypeError exception is raised when the list contains a value that cannot be compared. Consider this. Should the number 0 come before or after the word apple? However, if there is a combination of strings and integers in the iterable, a list of comprehension can be used for casting the iterables to the comparable data types.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Take this example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; mixed_numbers = [5, \"1\", 100, \"34\"]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(mixed_numbers)<\/span>\r\n\r\n<span style=\"font-weight: 400\">Traceback (most recent call last):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">TypeError: '&lt;' not supported between instances of 'str' and 'int'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # List comprehension to convert all values to integers<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; [int(x) for x in mixed_numbers]<\/span>\r\n\r\n<span style=\"font-weight: 400\">[5, 1, 100, 34]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted([int(x) for x in mixed_numbers])<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 5, 34, 100]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Every element present in the mixed_numbers has int() called on them for converting them into str values. Then, we can successfully compare every element using the sorted() function and provide a sorted output.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Python is capable of converting a value to another data type implicitly. Take the example below, where the result is a false statement which is converted to bool type where 1 is true and 0 is false.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; similar_values = [False, 0, 1, 'A' == 'B', 1 &lt;= 0]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(similar_values)<\/span>\r\n\r\n<span style=\"font-weight: 400\">[False, 0, False, False, 1]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">This example can be used for understanding sort stability. When you sort equal values in Python, the original order is retained in the output.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now, when you are comparing strings, the case matters. You can sort the values of a list of strings in ascending order, which means alphabetically. Take a look at this example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; names = ['Harry', 'Suzy', 'Al', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Al', 'Harry', 'Mark', 'Suzy']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">However, in Python, Unicode Code Point of the first letter is used for determining the order. This means when you are comparing Al and al, the result will not be the same. Here is an example where ord() is used for returning the first letter\u2019s Unicode Code Point.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; names_with_case = ['harry', 'Suzy', 'al', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names_with_case)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Mark', 'Suzy', 'al', 'harry']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # List comprehension for Unicode Code Point of first letter in each word<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; [(ord(name[0]), name[0]) for name in sorted(names_with_case)]<\/span>\r\n\r\n<span style=\"font-weight: 400\">[(77, 'M'), (83, 'S'), (97, 'a'), (104, 'h')]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The first character of each element is returned by name[0]. As you can see that the output has M first because even though a comes before M, the code point of a comes after M. If the first letter is the same, the second character is used for determining the order. This goes on till you reach the end of the string. Check this example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; very_similar_strs = ['hhhhhd', 'hhhhha', 'hhhhhc','hhhhhb']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(very_similar_strs)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['hhhhha', 'hhhhhb', 'hhhhhc', 'hhhhhd']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">If you have strings that have identical values with different lengths, the sorted() function will ascend them from shortest length to the largest length. Here is an example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; different_lengths = ['hhhh', 'hh', 'hhhhh','h']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(different_lengths)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['h', 'hh', 'hhhh', 'hhhhh']<\/span>\r\n\r\n<span style=\"font-weight: 400\">reverse Argument in sorted()\u00a0<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">For changing the behavior of sorting through the assigned Boolean, you have to use the reverse keyword argument. If you assign true to reverse, the sorting order will be descending.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; names = ['Harry', 'Suzy', 'Al', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Al', 'Harry', 'Mark', 'Suzy']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names, reverse=True)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Suzy', 'Mark', 'Harry', 'Al']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">To keep the order ascending, you can assign the False value. Check out the following example that will help you understand the reverse\u2019s behavior:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; names_with_case = ['harry', 'Suzy', 'al', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names_with_case, reverse=True)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['harry', 'al', 'Suzy', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; similar_values = [False, 1, 'A' == 'B', 1 &lt;= 0]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(similar_values, reverse=True)<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, False, False, False]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; numbers = [6, 9, 3, 1]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(numbers, reverse=False)<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 3, 6, 9]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">sorted() With a key Argument<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">They key argument is used on every value present in the list for determining the order of the output. For example, you want to sort a list on the basis of the length of the string, shortest to longest. Here is how you can do it using the key argument:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; word = 'paper'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; len(word)<\/span>\r\n\r\n<span style=\"font-weight: 400\">5<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; words = ['banana', 'pie', 'Washington', 'book']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(words, key=len)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['pie', 'book', 'banana', 'Washington']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The len() returns the length of the string which is then used to sort the list in ascending order. You can also use the key argument for sorting by first letter where the entire string is converted into lower case:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; names_with_case = ['harry', 'Suzy', 'al', 'Mark']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names_with_case)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Mark', 'Suzy', 'al', 'harry']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(names_with_case, key=str.lower)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['al', 'harry', 'Mark', 'Suzy']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">As you can see, the values haven\u2019t been converted into lowercase because there is no manipulation in the original list. When the sorting is taking place, the key is called on every item in the list for determining the order. The original value will not be changed in the output.<\/span><\/p>\n<p dir=\"ltr\">\n<p dir=\"ltr\"><span style=\"font-weight: 400\">When you are using the key argument, you will be facing the following limitations:<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. There can be only 1 argument than can be passed to the key argument in the function.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. The function where the key argument is used should be able to handle every value in the iterable.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Apart from this, the key argument is a powerful feature of Python that can be used with any user-defined or built-in functions for manipulating the order of the output.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">For example, if you want to sort a list using the last letter of the string, you need to define a function and use it. Take a look at this:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; def reverse_word(word):<\/span>\r\n\r\n<span style=\"font-weight: 400\">... \u00a0 \u00a0 return word[::-1]<\/span>\r\n\r\n<span style=\"font-weight: 400\">...<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; words = ['banana', 'pie', 'Washington', 'book']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(words, key=reverse_word)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['banana', 'pie', 'book', 'Washington']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">To reverse the string, the syntax word[::-1] is used. The reverse_word() is applied to every element.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now, here you could have used a lambda function instead of writing a standalone function. A lambda is an inline anonymous function with no name. It executes just like function but it doesn\u2019t have any statements. IN the following example, the lambda function is used to define key with no name. x is the argument of lambda and the operation performed on argument is x[::-1].<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; words = ['banana', 'pie', 'Washington', 'book']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(words, key=lambda x: x[::-1])<\/span>\r\n\r\n<span style=\"font-weight: 400\">['banana', 'pie', 'book', 'Washington']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">x[::-1]\u00a0 reverses the word for every element. As you can see, the original words have not been affected by the reversed output used for sorting. If you want to change the order of output as well, you can use the reverse keyword with the key argument.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; words = ['banana', 'pie', 'Washington', 'book']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted(words, key=lambda x: x[::-1], reverse=True)<\/span>\r\n\r\n<span style=\"font-weight: 400\">['Washington', 'book', 'pie', 'banana']<\/span><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"using-the-sort\"><\/span><b>Using the .sort()<\/b><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The .sort() function does more of less of the same thing as of sorted(). But there are two critical differences as highlighted by the help() documentation.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Python2<\/span>\r\n\r\n<span style=\"font-weight: 400\">Help on method_descriptor:<\/span>\r\n\r\n<span style=\"font-weight: 400\">sort(...)<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0cmp(x, y) -&gt; -1, 0, 1<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Python3<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; help(list.sort)<\/span>\r\n\r\n<span style=\"font-weight: 400\">Help on method_descriptor:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">sort(...)<\/span>\r\n\r\n<span style=\"font-weight: 400\">L.sort(key=None, reverse=False) -&gt; None -- stable sort *IN PLACE*<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">First of all, .sort() can only be used for lists as it is a method of list class. Second, it modifies the values and returns none. Take a look at the following example to understand the impact of these differences:<\/span><\/p>\n<blockquote>\n<pre><span style=\"font-weight: 400\">&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; values_to_sort = [5, 2, 6, 1]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Try to call .sort() like sorted()<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sort(values_to_sort)<\/span>\r\n\r\n<span style=\"font-weight: 400\">Traceback (most recent call last):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">NameError: name 'sort' is not defined<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Try to use .sort() on a tuple<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; tuple_val = (5, 1, 3, 5)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; tuple_val.sort()<\/span>\r\n\r\n<span style=\"font-weight: 400\">Traceback (most recent call last):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">AttributeError: 'tuple' object has no attribute 'sort'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Sort the list and assign to new variable<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; sorted_values = values_to_sort.sort()<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; print(sorted_values)<\/span>\r\n\r\n<span style=\"font-weight: 400\">None<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Print original variable<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; print(values_to_sort)<\/span>\r\n\r\n<span style=\"font-weight: 400\">[1, 2, 5, 6]<\/span><\/pre>\n<\/blockquote>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">There are two major differences that can be seen in this example:<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. The new variable can pass only a none type as .sort() has no ordered output.<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. The original order of the list is not maintained and the list of values_to_sort has been changed.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">There are reverse and key arguments available for .sort() as well. Here is an example of sorting a list by the third word\u2019s second letter and returning the list in reverse.<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; phrases = ['when in rome',\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">... \u00a0 \u00a0 'what goes around comes around',\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">... \u00a0 \u00a0 'all is fair in love and war'<\/span>\r\n\r\n<span style=\"font-weight: 400\">... \u00a0 \u00a0 ]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; phrases.sort(key=lambda x: x.split()[2][1], reverse=True)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; phrases<\/span>\r\n\r\n<span style=\"font-weight: 400\">['what goes around comes around', 'when in rome', 'all is fair in love and war']<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">As you can see, a lambda function is used for splitting every phrase in a list of words, finding the third word and then the second letter in that word.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"sorted-vs-sort\"><\/span><b>sorted()\u00a0vs\u00a0.sort()<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<figure id=\"attachment_165533\" aria-describedby=\"caption-attachment-165533\" style=\"width: 529px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-300x225.jpg\" alt=\"Sorted () vs Sort ()\" class=\"wp-image-165533\" width=\"529\" height=\"397\" title=\"\" srcset=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-300x225.jpg 300w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-150x113.jpg 150w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-600x450.jpg 600w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-220x165.jpg 220w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-667x500.jpg 667w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-595x446.jpg 595w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-510x382.jpg 510w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2-480x360.jpg 480w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/slide_2.jpg 960w\" sizes=\"(max-width: 529px) 100vw, 529px\" \/><figcaption id=\"caption-attachment-165533\" class=\"wp-caption-text\">Sorted () vs sort () source &#8211; slide player<\/figcaption><\/figure>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now that you have understood how sorted() and .sort() works, you need to understand when to use which. Take a look at this example:<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">There is a 5k race. Your task is to capture and sort the data. The data is the number of runner\u2019s bib and the seconds they took to finish the race:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; from collections import namedtuple<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; Runner = namedtuple('Runner', 'bibnumber duration')<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Every time a runner touches the finish line, they will be added to the runners list. Since in the 5k race, not everyone starts at the same time, the first person to reach the finishing line might not be the fastest one:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners = []<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('2528567', 1500))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('7575234', 1420))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('2666234', 1600))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('2425234', 1490))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('1235234', 1620))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # Thousands and Thousands of entries later...<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.append(Runner('2526674', 1906))<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now, the programmer has to figure out the top 5 runners that will get the prize and the list has to be sorted according to the fastest time. All you need to do is sort the list by duration and take the participants with the lowest time:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners.sort(key=lambda x: getattr(x, 'duration'))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; top_five_runners = runners[:5]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now, as you can see that a lambda function is used in the key argument for taking each runner\u2019s duration attribute.\u00a0 .sort() is used for sorting the time. The variable, top_five_runners, is used for storing the first 5 elements after the sorting is done.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">But now, they want to gift a gym bag to every 20<\/span><span style=\"font-weight: 400\">th<\/span><span style=\"font-weight: 400\"> person who crosses the finishing line. This is not going to be easy as the list has been irreversibly changed. You cannot get the original list in the order the runner\u2019s finished. In such case, .sort() is not the best option for you. If you are working on unimportant data, or you have a copy of the data, you can use the .sort().<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">So, instead of .sort(), you should have used the sorted() with the lambda function. Here is how you can do it:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; runners_by_duration = sorted(runners, key=lambda x: getattr(x, 'duration'))<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; top_five_runners = runners_by_duration[:5]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now that you have used the sorted(), the original data has not been overwritten and is still intact. To find every 20<\/span><span style=\"font-weight: 400\">th<\/span><span style=\"font-weight: 400\"> person to reach the finish line can be done using the following:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; every_twentieth_runners = runners[::20]<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">So basically, both sorted() and .sort() give the same exact order can be used with key and reverse argument in the same fashion. However, when it comes to in-place modifications and output, both of them have different characteristics. <\/span><\/p>\n<p dir=\"ltr\">\n<p dir=\"ltr\"><span style=\"font-weight: 400\">As .sort() can irreversibly overwrite data, make sure that you think through before using it any program or application functionality.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">To become an expert in sort functions, you need to practice with complex data types like nested iterables. You can try <\/span><span style=\"font-weight: 400\">Timsort<\/span><span style=\"font-weight: 400\"> for understanding the implementation of open-source Python code for built-ins and sort algorithms.\u00a0<\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"final-thoughts\"><\/span>Final Thoughts<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p dir=\"ltr\">You can become a Python coding language master and a highly-skilled Python programmer with a <a href=\"https:\/\/www.digitalvidya.com\/python-course\/\">Python programming course<\/a>. Any aspiring programmer can learn from the basics of Python after the course and keep mastering Python.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python provides two methods for organizing and customizing various types of data into different data structures. We will cover the implementation of simple ordering and sorting of data structures in Python in this article, the difference between sort) (and sorted) (and the configuration of a complicated sort order. Sorting is very easy in Python as [&hellip;]<\/p>\n","protected":false},"author":12960,"featured_media":165741,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[11144],"tags":[11311,11312,11313,11314,11315],"class_list":["post-164820","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-science","tag-sort-in-python","tag-sort-list-python","tag-sorting-in-python","tag-how-to-sort-a-list-in-python","tag-sorted-python"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts\/164820","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/users\/12960"}],"replies":[{"embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/comments?post=164820"}],"version-history":[{"count":0,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts\/164820\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/media\/165741"}],"wp:attachment":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/media?parent=164820"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/categories?post=164820"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/tags?post=164820"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}