{"id":164818,"date":"2019-11-19T16:56:26","date_gmt":"2019-11-19T11:26:26","guid":{"rendered":"https:\/\/www.digitalvidya.com\/blog\/?p=164818"},"modified":"2022-04-28T17:33:59","modified_gmt":"2022-04-28T12:03:59","slug":"how-to-implement-a-python-stack","status":"publish","type":"post","link":"https:\/\/www.digitalvidya.com\/blog\/how-to-implement-a-python-stack\/","title":{"rendered":"A Comprehensive Tutorial on How to Implement a Python Stack"},"content":{"rendered":"<p dir=\"ltr\"><span style=\"font-weight: 400\">A Stack is a data framework used to store Last-In \/ First-Out fashion items that are popularly referred to as LIFO. It is unlike the First-In \/ First-Out (FIFO) queue. The key to understanding stack is to think about it in any text editor like the undo app. You&#8217;re editing a Python script, for example. You&#8217;ve added a new feature. This means adding to the undo stack a new item.<\/span><\/p>\n<p dir=\"ltr\">There is an operation to insert a function in the stack. After adding the feature, you can delete a word from a post. Even the undo stack is added to this deletion. Each new command is placed at the top as these commands are stored in the undo stack. The inclusion of new items is referred to as Push when interacting with the stacks.<\/p>\n<p dir=\"ltr\"><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\/164818#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\/164818' \/><\/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=\"45\"\/><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><\/p>\n<p dir=\"ltr\">Now, all these changes you want to undo, so you give the undo button. It will take most of the element in the stack, in this case indenting the post, and delete it from the stack. The editor must undo the indent and the undo stack now contains just two objects.<\/p>\n<div class=\"ast-oembed-container \" style=\"height: 100%;\"><iframe title=\"How to Implement Stack in Python\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/E6K9ArfQXxw?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/div>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">This operation is the exact opposite of push and is named as Pop. When you give the undo command again, the next item on the stack will get popped off.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Once the stack is empty, giving the undo command will have no effect as the stack will be empty. Here is how you can implement a Python stack:<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">When you try to implement a Python stack, you have to consider a couple of options. Here we will be focusing on using the data structures provided by the Python library instead of using any third-party packages or writing your own.<\/span><\/p>\n<figure id=\"attachment_165521\" aria-describedby=\"caption-attachment-165521\" style=\"width: 521px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/download-300x168.png\" alt=\"Stacks in Python\" class=\"wp-image-165521\" width=\"521\" height=\"292\" title=\"\"><figcaption id=\"caption-attachment-165521\" class=\"wp-caption-text\">Stacks in python source &#8211; dan bader<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"list\"><\/span><b>List<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">When you are building a stack, the most frequently used data structure in the program is the built-in list. For adding new elements to the stack, you have to use .append() instead of .push(). For removing the elements in the order of LIFO, you have to use .pop().\u00a0<\/span><\/p>\n<p dir=\"ltr\">\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The major operations that you can do on a stack through lists are:<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. Pushing an element<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. Popping an element<\/span><\/p>\n<p><span style=\"font-weight: 400\">3. Getting the stack\u2019s size<\/span><\/p>\n<p><span style=\"font-weight: 400\">4. Printing all the items present in the stack<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Take a look at the following example:<\/span><\/p>\n<pre><span style=\"font-weight: 400\">class Stack:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Constructor creates a list<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def __init__(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.stack = list()<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Adding elements to stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def push(self,data):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0#Checking to avoid duplicate entries<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if data not in self.stack:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.stack.append(data)<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return True<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return False<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Removing last element from the stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def pop(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if len(self.stack)&lt;=0:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return (\"Stack Empty!\")<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return self.stack.pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/span><\/pre>\n<pre><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Getting the size of the stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def size(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return len(self.stack)<\/span>\r\n\r\n<span style=\"font-weight: 400\">myStack = Stack()<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.push(5)) #prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.push(6)) #prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.push(9)) #prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.push(5)) #prints False since 5 is there<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.push(3)) #prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.size())\u00a0 #prints 4\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.pop()) \u00a0 #prints 3<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.pop()) \u00a0 #prints 9<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.pop()) \u00a0 #prints 6<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.pop()) \u00a0 #prints 5<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.size())\u00a0 #prints 0<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(myStack.pop()) \u00a0 #prints Stack Empty!<\/span>\r\n\r\n<span style=\"font-weight: 400\">Here is another example of Python\u2019s implementation of stack using lists:<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">=<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">[]<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'a'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'b'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'c'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span>\r\n\r\n<span style=\"font-weight: 400\">['a', 'b', 'c']<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'c'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'b'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'a'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/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 <\/span><span style=\"font-weight: 400\">\"&lt;console&gt;\"<\/span><span style=\"font-weight: 400\">, line <\/span><span style=\"font-weight: 400\">1<\/span><span style=\"font-weight: 400\">, in <\/span><span style=\"font-weight: 400\">&lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">IndexError<\/span><span style=\"font-weight: 400\">: <\/span><span style=\"font-weight: 400\">pop from empty list<\/span>\r\n\r\n<span style=\"font-weight: 400\">As you can see in the above code, an IndexError was raced after the final command was executed because the stack was empty and you can\u2019t call a .pop() on an empty stack.\u00a0<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The best advantage of using list for implementing a stack in Python is that it is familiar. If you have any previous experience as a programmer, you must be familiar with lists and how they can be used in a program.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">However, when compared to other data structures, there are a few shortcomings of using list as a data structure for implementing stack. The main issue is the issue of speed it faces as the list expands. The goal of storing items in a list is so that it can provide fast access to random elements. This means that at high level, all these items are stored adjacent to each other in memory.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\"> When the stack gets bigger than the block of memory holding it currently, there are some memory allocations done by Python. This means that execution of .append() call will take much longer than usual. Another less serious problem is that adding an element in the stack at other than the last position takes a significantly longer amount of time. The issue of reallocation is fixed by the next data structure.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"collectionsqueue\"><\/span><b>Collections.queue<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<figure id=\"attachment_165522\" aria-describedby=\"caption-attachment-165522\" style=\"width: 450px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/download.jpg\" alt=\"Deque\" class=\"wp-image-165522\" width=\"450\" height=\"337\" title=\"\" srcset=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/download.jpg 259w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/download-150x112.jpg 150w, https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/download-220x165.jpg 220w\" sizes=\"(max-width: 450px) 100vw, 450px\" \/><figcaption id=\"caption-attachment-165522\" class=\"wp-caption-text\">Deque source &#8211; slideshare<\/figcaption><\/figure>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Deque is present in the collections module and is used to create Python stacks. It stands for double ended queue. The same .append() and .pop() operations are used on the deque. Take a look at the following example:<\/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; <\/span><span style=\"font-weight: 400\">from<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">collections<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">import<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">deque<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">=<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">deque()<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'a'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'b'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">append(<\/span><span style=\"font-weight: 400\">'c'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span>\r\n\r\n<span style=\"font-weight: 400\">deque(['a', 'b', 'c'])<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'c'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'b'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'a'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">pop()<\/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 <\/span><span style=\"font-weight: 400\">\"&lt;console&gt;\"<\/span><span style=\"font-weight: 400\">, line <\/span><span style=\"font-weight: 400\">1<\/span><span style=\"font-weight: 400\">, in <\/span><span style=\"font-weight: 400\">&lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">IndexError<\/span><span style=\"font-weight: 400\">: <\/span><span style=\"font-weight: 400\">pop from an empty deque<\/span><\/pre>\n<\/blockquote>\n<p><span style=\"font-weight: 400\">This example must look similar to the example of list. This begs the questions as to why there was a need for two data structures that have the same implementation. There is a reason behind this.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">As mentioned before, list is built on contiguous memory\u2019s blocks. This means that all the items present in the list are stored next to each other. This adjacent storing of items works great for operations like list indexing. <\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">For example, getting the third item on the list through myList[2] will not take much time as Python will know exactly where it has to search in memory to get the item. This layout of the memory also facilitates allowing of slices to work on lists. <\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">The contiguous memory layout is also the reason why the .append() operation takes more time in lists. When the contiguous memory block gets full, a new block is needed which makes the .append() operation take even more time.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Dequeu is based on the doubly linked list. When it comes to the structure of the linked list, every item has its own memory block and a reference to the next item in the list. A doubly linked list also has the same features except one difference where each item has a reference to the next as well as previous item of the list. <\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">So addition of a node to either end of the list is easier as compared to other types of data structures. When you add a new item to a linked list, the only thing you have to do is to set the reference of the new item to the top of the stack and then point the stack\u2019s top to the new item.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">However, this addition and removal of items from the stack has a trade-off. Now when you have to get the 4<\/span><span style=\"font-weight: 400\">th<\/span><span style=\"font-weight: 400\"> item from the list, it will take a longer time than it took for a list. This is because now Python will have to walk through every item of the list to get to the fourth one. <\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Luckily, this random slicing and indexing is very rare on a stack. Push and Pop make up the majority of the stack operations. This also makes deque one of the best choices for implementation of Python stack.<\/span><\/p>\n<p dir=\"ltr\">\n<h2><span class=\"ez-toc-section\" id=\"array\"><\/span><b>Array<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">For the agnostic implementation of Stack, you have to use arrays. The only difference here is that unlike lists, arrays have a fixed size. Also, there is a top pointer that is used for keeping a tab on the stack\u2019s status. Here is an algorithm that can be used for implementing Python stack using arrays:<\/span><\/p>\n<p><span style=\"font-weight: 400\">1. The first step is declaring an integer with the name MaxSize that represents the stack\u2019s maximum size and a list.<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. Set the top to 0.<\/span><\/p>\n<p><span style=\"font-weight: 400\">3. This step is performing the Push operation. For this, you need to:<\/span><\/p>\n<p style=\"padding-left: 40px\"><span style=\"font-weight: 400\">\u21d2 Check if the Stack\u2019s MaxSize is more than the Top.<\/span><\/p>\n<p style=\"padding-left: 40px\"><span style=\"font-weight: 400\">\u21d2 If no, print the message stating that stack is full.<\/span><\/p>\n<p style=\"padding-left: 40px\"><span style=\"font-weight: 400\">\u21d2 If yes, then add the data to stack and increase the top by 1.<\/span><\/p>\n<p><span style=\"font-weight: 400\">4. Next is implementing the pop operation. Follow these steps:<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u21d2 Check is top is more than 0 or not.<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u21d2 If no, print the message stating that stack is empty.<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u21d2 If yes, remove the last item from the list and decrease top by 1.<\/span><\/p>\n<p><span style=\"font-weight: 400\">5. For getting the size of the stack, you just need to get the value of the top pointer.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Take a look at the following code:<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">class Stack:<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0<\/span><\/p>\n<pre><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Constructor\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def __init__(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.stack = list()<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.maxSize = 8<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.top = 0<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0<\/span><\/p>\n<pre><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Adds element to the Stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def push(self,data):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if self.top&gt;=self.maxSize:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return (\"Stack Full!\")<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.stack.append(data)<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.top += 1<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return True<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/span><\/pre>\n<pre><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Removes element from the stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def pop(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if self.top&lt;=0:<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return (\"Stack Empty!\")<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0item = self.stack.pop()<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.top -= 1<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return item<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0#Size of the stack<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0def size(self):<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return self.top<\/span>\r\n\r\n<span style=\"font-weight: 400\">s = Stack()<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(1))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(2))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(3))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(4))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(5))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(6))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(7))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(8))#prints True<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.push(9))#prints Stack Full!<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.size())#prints 8\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 8<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 7<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 6<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 5<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 4<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 3<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 2<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints 1<\/span>\r\n\r\n<span style=\"font-weight: 400\">print(s.pop())#prints Stack Empty!<\/span><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"stacks-and-threading\"><\/span><b>Stacks and Threading<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<figure id=\"attachment_165523\" aria-describedby=\"caption-attachment-165523\" style=\"width: 458px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.digitalvidya.com\/blog\/wp-content\/uploads\/2019\/09\/Python-Thread-State-460x359_7218a1fcd4221d53911d95c7026d8d16.png\" alt=\"Python Thread State\" class=\"wp-image-165523\" width=\"458\" height=\"357\" title=\"\"><figcaption id=\"caption-attachment-165523\" class=\"wp-caption-text\">Python thread state source -uber<\/figcaption><\/figure>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Python stacks have also found application in multi-threaded programs. If your program has threads, the lists and dequeue options will behave differently. For starters, for any data structure to which multiple threads have access, list shouldn\u2019t be used.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Deque is a little more complicated. The .append() and .pop() operations involved in the deque are atomic in nature which means a different thread can\u2019t interrupt them. So, you will be thread use if you use only the .append() and .pop() operations.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\"> However, if there are other methods in the class, especially the ones that are not designed specifically to be atomic, then deque is not thread-safe. So, if you are using deque for creating a Python stack that is thread-safe, you are exposing yourself to cause race conditions and misuse it in the future.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">So now that list and deque are out of the options for building Python stack for a threaded program, what can you do? The answer is queue.LifoQueue, present in the queue model.\u00a0<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Just like list and deque, LifoQueue uses .get() and .put() for adding and removing items from the stack:<\/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; <\/span><span style=\"font-weight: 400\">from<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">queue<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">import<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">LifoQueue<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">=<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">LifoQueue()<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">put(<\/span><span style=\"font-weight: 400\">'a'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">put(<\/span><span style=\"font-weight: 400\">'b'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">put(<\/span><span style=\"font-weight: 400\">'c'<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span>\r\n\r\n<span style=\"font-weight: 400\">&lt;queue.LifoQueue object at 0x7f408885e2b0&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">get()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'c'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">get()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'b'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">get()<\/span>\r\n\r\n<span style=\"font-weight: 400\">'a'<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; # myStack.get() &lt;--- waits forever<\/span>\r\n\r\n<span style=\"font-weight: 400\">&gt;&gt;&gt; <\/span><span style=\"font-weight: 400\">myStack<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">get_nowait()<\/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 <\/span><span style=\"font-weight: 400\">\"&lt;console&gt;\"<\/span><span style=\"font-weight: 400\">, line <\/span><span style=\"font-weight: 400\">1<\/span><span style=\"font-weight: 400\">, in <\/span><span style=\"font-weight: 400\">&lt;module&gt;<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File <\/span><span style=\"font-weight: 400\">\"\/usr\/lib\/Python3.7\/queue.py\"<\/span><span style=\"font-weight: 400\">, line <\/span><span style=\"font-weight: 400\">198<\/span><span style=\"font-weight: 400\">, in <\/span><span style=\"font-weight: 400\">get_nowait<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0<\/span><span style=\"font-weight: 400\">return<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">self<\/span><span style=\"font-weight: 400\">.<\/span><span style=\"font-weight: 400\">get(block<\/span><span style=\"font-weight: 400\">=<\/span><span style=\"font-weight: 400\">False<\/span><span style=\"font-weight: 400\">)<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0File <\/span><span style=\"font-weight: 400\">\"\/usr\/lib\/Python3.7\/queue.py\"<\/span><span style=\"font-weight: 400\">, line <\/span><span style=\"font-weight: 400\">167<\/span><span style=\"font-weight: 400\">, in <\/span><span style=\"font-weight: 400\">get<\/span>\r\n\r\n<span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0<\/span><span style=\"font-weight: 400\">raise<\/span><span style=\"font-weight: 400\"> <\/span><span style=\"font-weight: 400\">Empty<\/span>\r\n\r\n<span style=\"font-weight: 400\">_queue.Empty<\/span><\/pre>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">LifeQueue is completely thread-safe meaning you can use all its methods for creating a safe threaded environment. There is also an option of adding timeouts to the operations which is a must-have feature for threaded programs. But, there is a cost to this full thread safety. To get this safety, each operation requires a little extra work meaning it takes longer time to execute. However, this will not slow down the speed of your entire program. You can carefully make a switch to deque if you have discovered that the stack operations are bottleneck and measured the performance of the program.<\/span><\/p>\n<h2><span class=\"ez-toc-section\" id=\"which-implementation-should-be-used\"><\/span><b>Which implementation should be used?<\/b><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">If you are not threading, you should go for the deque data structure. Use the LifQueue if you have to use threading unless you are willing to take the maintenance risks in exchange for a small increase in speed for popping and pushing items by measuring the performance of the program.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">You might feel comfortable using lists for implementing stacks but it is usually avoided by developers due to the issues of memory reallocation. Both lists and deque have the same interface and deque doesn\u2019t have the memory reallocation issues which makes it the best option for implementing non-threaded Python stack.<\/span><\/p>\n<p dir=\"ltr\"><span style=\"font-weight: 400\">Now that you know what stack is and how you can implement it, you will be able to select the right implementation method for your problem.\u00a0<\/span><\/p>\n<p dir=\"ltr\">\n<h3><span class=\"ez-toc-section\" id=\"final-thoughts\"><\/span><strong>Final Thoughts<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p dir=\"ltr\">With taking a <a href=\"https:\/\/www.digitalvidya.com\/python-course\/\">Python course<\/a>, you can become a Python coding language master that will not only enhance your resume value but will also ensure a better career.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A Stack is a data framework used to store Last-In \/ First-Out fashion items that are popularly referred to as LIFO. It is unlike the First-In \/ First-Out (FIFO) queue. The key to understanding stack is to think about it in any text editor like the undo app. You&#8217;re editing a Python script, for example. [&hellip;]<\/p>\n","protected":false},"author":16370,"featured_media":165720,"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":[11307,11308,11309,11310],"class_list":["post-164818","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-science","tag-stack-in-python","tag-python-stack","tag-stacks-in-python","tag-stack-program-in-python"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts\/164818","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\/16370"}],"replies":[{"embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/comments?post=164818"}],"version-history":[{"count":0,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/posts\/164818\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/media\/165720"}],"wp:attachment":[{"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/media?parent=164818"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/categories?post=164818"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.digitalvidya.com\/blog\/wp-json\/wp\/v2\/tags?post=164818"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}