Write a Python program to implement stack using list

Stack in Python

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.

The functions associated with stack are:

  • empty() – Returns whether the stack is empty – Time Complexity: O(1)
  • size() – Returns the size of the stack – Time Complexity: O(1)
  • top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
  • push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
  • pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

How to Implement a Python Stack

by Jim Anderson basics python

Mark as Completed

Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: How to Implement a Python Stack

Have you heard of stacks and wondered what they are? Do you have the general idea but are wondering how to implement a Python stack? You’ve come to the right place!

In this tutorial, you’ll learn:

  • How to recognize when a stack is a good choice for data structures
  • How to decide which implementation is best for your program
  • What extra considerations to make about stacks in a threading or multiprocessing environment

This tutorial is for Pythonistas who are comfortable running scripts, know what a list is and how to use it, and are wondering how to implement Python stacks.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Python Program to Implement a Stack using Linked List

PythonServer Side ProgrammingProgramming

When it is required to implement a stack data structure using a linked list, a method to add (push values) elements to the linked list, and a method to delete (pop values) the elements of the linked list are defined.

Below is a demonstration for the same −

Using List as Stack and Queues in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about Stack & Queue structures in Python 3.x. Or earlier. Here we will discuss the working and modification within these data structures −

This includes −

  1. Insertion operation (Push, Enqueue)
  2. Deletion operation (Pop, Dequeue)
  3. Display / Traversing Operation

Prerequisites: List & List Operations

Related Data Structure: List Manipulation

How to implement stack in Python

A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:

  • Push: Add an element to the stack
  • Pop: Remove an element from the stack
  • Peek: Get the topmost element of the stack

stack

In Python, a stack is implemented using a list object.

  • To push an item in the stack, use the list function append list.append(item)
  • To pop an item in the stack, use the list function pop list.pop()
  • To get the top most item in the stack, write list[-1]

The following illustration explains the concept:

1 of 6

1 of 6

1 of 6

1 of 6

1 of 6

4.5. Implementing a Stack in Python¶

Now that we have clearly defined the stack as an abstract data type we will turn our attention to using Python to implement the stack. Recall that when we give an abstract data type a physical implementation we refer to the implementation as a data structure.

As we described in Chapter 1, in Python, as in any object-oriented programming language, the implementation of choice for an abstract data type such as a stack is the creation of a new class. The stack operations are implemented as methods. Further, to implement a stack, which is a collection of elements, it makes sense to utilize the power and simplicity of the primitive collections provided by Python. We will use a list.

Recall that the list class in Python provides an ordered collection mechanism and a set of methods. For example, if we have the list [2,5,3,6,7,4], we need only to decide which end of the list will be considered the top of the stack and which will be the base. Once that decision is made, the operations can be implemented using the list methods such as append and pop.

The following stack implementation (ActiveCode 1) assumes that the end of the list will hold the top element of the stack. As the stack grows (as push operations occur), new items will be added on the end of the list. pop operations will manipulate that same end.

Remember that nothing happens when we click the run button other than the definition of the class. We must create a Stack object and then use it. ActiveCode 2 shows the Stack class in action as we perform the sequence of operations from Table 1. Notice that the definition of the Stack class is imported from the pythonds module.

Note

The pythonds module contains implementations of all data structures discussed in this book. It is structured according to the sections: basic, trees, and graphs. The module can be downloaded from GitHub. or installed from the command line using pip install pythonds.

It is important to note that we could have chosen to implement the stack using a list where the top is at the beginning instead of at the end. In this case, the previous pop and append methods would no longer work and we would have to index position 0 (the first item in the list) explicitly using pop and insert. The implementation is shown in CodeLens 1.

Activity: CodeLens Alternative Implementation of the Stack class (stack_cl_1)

This ability to change the physical implementation of an abstract data type while maintaining the logical characteristics is an example of abstraction at work. However, even though the stack will work either way, if we consider the performance of the two implementations, there is definitely a difference. Recall that the append and pop() operations were both O(1). This means that the first implementation will perform push and pop in constant time no matter how many items are on the stack. The performance of the second implementation suffers in that the insert(0) and pop(0) operations will both require O(n) for a stack of size n. Clearly, even though the implementations are logically equivalent, they would have very different timings when performing benchmark testing.

Self Check

    Q-4: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?

    m = Stack() m.push('x') m.push('y') m.pop() m.push('z') m.peek()

  • 'x'
  • Remember that a stack is built from the bottom up.
  • 'y'
  • Remember that a stack is built from the bottom up.
  • 'z'
  • Good job.
  • The stack is empty
  • Remember that a stack is built from the bottom up.

    Q-5: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?

    m = Stack() m.push('x') m.push('y') m.push('z') while not m.isEmpty(): m.pop() m.pop()

  • 'x'
  • You may want to check out the docs for isEmpty
  • the stack is empty
  • There is an odd number of things on the stack but each time through the loop 2 things are popped.
  • an error will occur
  • Good Job.
  • 'z'
  • You may want to check out the docs for isEmpty

Write a function revstring(mystr) that uses a stack to reverse the characters in a string.

Top-Paying Programming Certifications for 2022

By KnowledgeHut

Programming is at the core of software development, which is why there is a huge demand for programmers—a demand that is growing exponentially and is expected to rise at a steady rate even in the future. In today’s world, just about everything is getting automated and digitization has become the new normal.Recruiters are on the lookout for professionals who have solid programming and full-stack development skills. Every recruiting agency and organizational HR recruiting team has put in place a thorough screening process, and this active hiring in startups, SMEs, and multinational companies has raised the bar for many aspiring programmers. Having a software development, web development, or programming certification will give you an upper hand at the time of recruitment. A certification from a reputed accreditation body will validate your skills and make you stand out among your peers.Having an extra certification apart from your UG or PG degree makes you a better fit for the job role in which you have an interest. But before you opt for any certification, you need to understand which programming language will take you where; and the potential benefits of pursuing a certification course of that particular programming language.In this article, you will get to know about the top programming certifications of 2022 and how to achieve them.What are Programming certifications?Programming certifications are exam-oriented and verify your skill and expertise in that field. Different organizations provide different programming certification exams that define your level, skills, and abilities vis `a vis that programming language. Having a programming certification will give you an edge over other peers and will highlight your coding skills.Most Popular Programming CertificationsC & C++ CertificationsOracle Certified Associate Java Programmer OCAJPCertified Associate in Python Programming (PCAP)MongoDB Certified Developer Associate ExamR Programming CertificationOracle MySQL Database Administration Training and Certification (CMDBA)CCA Spark and Hadoop Developer1. C & C++ CertificationsRegardless of your specialization in your UG or PG courses, clearing a developer-rated certification will not only make your resume stand out from others but also enhance your skills and boost your confidence. We have curated the top-most and popularly available certifications with descriptions that can help you decide which one is appropriate for your career path.C & C++ Certifications: C and C++ are often called the mother of Procedure-oriented and Object-oriented programming languages, which is absolutely true. These two programming languages have been around for many decades. Colleges and universities all over the world teach these as the base language. To get global recognition for the C and C++ certification, C++ Institute and Pearson VUE decided to carve a niche in this part of the certification landscape by offering the world's first international C/C++ certifications.Aspirants and professionals can choose either C or C++ as a career option/path and climb the certification ladder from associate to professional to senior. The C Programming Language Certified Associate (CLA) and C++ Certified Associate Programmer (CPA) are the core and first-level C and C++ certifications.CLA comprises of topics likeIntroduction to compiling and software development;Basic scalar data types and their operators;Flow control;Complex data types: arrays, structures and pointers;Memory management;Files and streams;Structuring the code: functions and modules;Preprocessor directives and complex declarations.CPA comprises of topics likeIntroduction to compiling and software development;Basic scalar data types, operators, flow control, streamed input/output, conversions;Declaring, defining and invoking functions, function overloading;Data aggregates;String processing, exceptions handling, dealing with namespaces;Object-oriented approach and its vocabulary;Dealing with classes and objects, class hierarchy and inheritance;Defining overloaded operators, user-defined operators, exceptions;Demand and Benefits: Having a CLA certification verifies that the programmer or the aspirant has an understanding of all the necessary and essential universal concepts of computer programming and developer tools. The course also covers all the syntax and semantics of different C constructs plus the data types offered by the language. This course brings crisp knowledge on writing programs using standard language infrastructure regardless of the hardware or software platform.A C++ Certified Associate Programmer (CPA) certification will give you an upper hand because it comprises syntax and semantics of the C++ language plus basic C++ data types. Apart from that, it contains principles of the object-oriented model and C++ implementation. Also, you will get to know about the various C++ standard libraries through this certification process. The average entry-level salary of a C/C++ developer with this certification will be $ 7,415 per annum. With two to three years of experience, the average salary hikes to $ 10,593 annually.Top companies and industries hiring CLA and CPA are Philips, Calsoft Pvt. Ltd., Cognizant, Synopsys Inc., private universities, Mphasis, etc.Where to take Training for Certification: CPP Institute has all the study resources you need to prepare for this examination. Apart from that, you can study from YouTube free resources.Who should take the Training (roles) for Certification: Any programmer or computer science aspirant - who wants to expand their knowledge of C/C++ or start their career as a C/C++ programmer or developer can opt for this certification course. There is no other prerequisite to appear for this exam.Course fees for Certification:CLA Certification:$ 147.50 (50% discount voucher)CPA Certification:$ 147.50 (50% discount voucher)Exam fee for certification:CLA Certification:$ 295CPA Certification:$ 295Retake fee for certification: Aspirants who have paid the complete exam price (USD 295) or have completed a course aligned with certification in the self-study mode (50% discount voucher) can have a free retake of the CPA or CLA exam. There is no limit to the number of times a candidate may retake the exam. You must wait 15 days before being allowed to re-sit that exam.2. Oracle Certified Associate Java Programmer OCAJPThis is a Java programming certification provided by Oracle. Java is among the most popular programming languages. James Gosling is the creator of Java which was earlier named Oak. It is a robust, high-level, general-purpose, pure object-oriented programming language developed by Sun Microsystems (now part of Oracle). Java consistently tops the 'most used programming languages’ list and is one of the most extensively used software development platforms. If you have the plan to get a proper training course online before appearing for the certification exam, KnowledgeHut (//www.knowledgehut.com/programming/java-training) has that for you.It is the preliminary and most basic certification provided by Oracle for Java. It helps gain fundamental understanding of Java programming and builds a foundation in Java and other general programming concepts. The certification encompasses two subcategories –OCAJP Java Standard Edition 8 (OCAJP 8) and OCAJP Java Standard Edition 11 (OCAJP 11)It comprises of topics likeJava BasicsWorking with Java Data TypesUsing Operators and Decision ConstructsCreating and Using ArraysUsing Loop ConstructsWorking with Methods and EncapsulationWorking with InheritanceHandling ExceptionsClass Methods and EncapsulationDescribing and Using Objects and ClassesHandling ExceptionsJava Technology and the Java Development EnvironmentInheritance and InterfacesUnderstanding ModulesUsing Operators and Decision ConstructsWorking with Java ArraysWorking with Selected classes, Java Primitive Data Types and String APIsDemand and Benefits: Having an OCAJP certification verifies that the aspirant has all the necessary and essential skills to become an expert Java developer. This certification also helps in getting an internship or entry-level jobs in different organizations. The entry-level salary of a junior Java developer with this certification is $ 3670 per annum; when the candidate gathers two to three years of experience, the average salary hikes to $ 5430 annually.Top companies and industries hiring Oracle Certified Associate Java Programmers are Smart Monitor Pvt. Ltd., Fiserv, Micron Semiconductor Asia Pvt. Ltd., private universities and many others.Where to take Training for Certification: KnowledgeHut has a fascinating course opportunity for beginners in Java programming. It has workshops with hands-on learning and 40 hours of instructor-led online lectures. Apart from that, Oracle also provides exam vouchers for this certification course.Who should take the Training (roles) for Certification: Any programmer or computer science aspirant - who wants to settle as a Java developer or start his/her career as a Java programmer can opt for this certification course. There is no other prerequisite to appear for this exam.Course fee for Certification:$ 245Application fee for certification:OCAJP8: $ 245OCAJP11: $ 249Exam fee for certification:OCAJP8: $ 245OCAJP11: $ 255Retake fee for certification: Aspirants can retake the exam if the exam voucher has a free retake option. If the exam retake option is available, one can opt for the exam after 14 days.3. Certified Associate in Python Programming (PCAP)Python is an interpreted, general-purpose, and high-level programming language developed by Guido Van Rossum. Python released in 1991 and within 5 to 6 years, this programming language become the most popular and widely used programming language in various disciplines. Today, companies use Python for GUI and CLI-based software development, web development (server-side), data science, machine learning, AI, robotics, drone systems, developing cyber-security tools, mathematics, system scripting, etc. PCAP is a professional Python certification credential that measures your competency in using the Python language to create code and your fundamental understanding of object-oriented programming.It comprises of topics likeBasic concepts of PythonOperators & data typesControl and EvaluationsModules and PackagesData AggregatesException HandlingStringsFunctions and ModulesObject-Oriented ProgrammingList Comprehensions, Lambdas, Closures, and I/O OperationsClasses, Objects, and ExceptionsDemand and Benefits: Having a Python certification verifies that the programmer or the aspirant has all the necessary and essential skills needed to become an expert Python developer. This certification also helps in getting an internship or entry-level jobs in different organizations. The average entry-level salary of a Python developer starts at around $100k per annum. With a few years of experience, the average salary hikes to $ 105k annually.Top companies and organizations hiring certified Python programmers are Bank of America, Atlassian, Google, Adobe, Apple, Cisco Systems, Intel, Lyft, IBM, etc.Where to take Training for Certification: KnowledgeHut has a fascinating course opportunity for beginners in Python programming. It has hands-on learning with 24 hours of instructor-led online lectures. Apart from that, the course has 100 hours of MCQs and three live projects.Who should take the Training (roles) for Certification: Any programmer, graduate, post graduate student, or computer science aspirant - who wants to pursue a career as a Python developer or Python programmer can opt for this certification training. There is no other prerequisite to appear for this exam.Course fees for Certification: $ 295Exam fee for certification:$ 295Retake fee for certification: If a candidate fails the exam, he/she has to wait for 15 days before being allowed to retake the exam for free. There is no limit to the number of times a candidate may retake an exam.4. MongoDB Certified Developer Associate ExamMongoDB is a NoSQL, document-based high-volume heterogeneous database system. Instead of having tables with rows and columns, MongoDB uses a collection of documents. It is a database development system that provides scalability and flexibility as per query requirements. Its document models are easy to implement for developers and can meet complex demands at scale.MongoDB created this MongoDB Certified Developer Associate Exam for individuals who require to verify their knowledge on fundamentals of designing and building applications using MongoDB. They recommend this certification for those who want to become software engineers and have a solid understanding of core MongoDB along with professional experience.It comprises of topics likeMongoDB BasicsCRUDIndexing and PerformanceThe MongoDB Aggregation FrameworkBasic Cluster AdministrationAggregation & ReplicationShardingMongoDB Performance MongoDB for Python DevelopersMongoDB for Java Developers or MongoDB for JavaScript DevelopersData ModelingDemand and Benefits: Having a MongoDB Certified Developer Associate Exam certification verifies that the programmer or the aspirant has all the necessary and essential skills to become a NoSQL database expert. The MongoDB certification is inexpensive and in demand. The average salary for a software developer with MongoDB skills starts from $ 8200 per annum.Top companies and organizations hiring certified MongoDB developers are Accenture, Collabera, Leoforce LLC., Adobe, Trigent Software, Lyft, etc.Where to take Training for Certification: KnowledgeHut has a comprehensive course structure for those who want to learn MongoDB & Mongodb Administrator. It has 24+ hours of instructor-led online lectures and 80+ hours of hands-on with cloud labs. This self-paced course also includes capstone projects to give participants a feel of real world working. Who should take the Training (roles) for Certification: Any programmer, graduate, post graduate student, experienced developer or computer science aspirant - who wants to embark on a career as a MongoDB developer or start his/her career as a NoSQL database expert or do better in their current role as a MongoDB developer can opt for this certification course. There is no other prerequisite to appear for this exam.Course fees for Certification: $ 150Exam fee for certification:$ 150Retake fee for certification: MongoDB University is no longer allowing a free retake with the exam fee. The candidate has to pay an additional $10 to reschedule or retake the exam.5. R Programming CertificationIt is a part of the data science specialization from Johns Hopkins University under Coursera. This course teaches R programming for efficient data analysis. It covers different R programming concepts like building blocks of R, datatypes, reading data into R from external files, accessing packages, writing functions, debugging techniques, profiling R code, and performing analysis.It comprises of topics like:Basic building blocks in RData types in RControl StructuresScoping Rules - OptimizationCoding StandardsDates and TimesFunctionsLoopingDebugging toolsSimulating data in RR ProfilerDemand and Benefits: Having an R Programming certification verifies that the programmer or the aspirant has all the necessary and essential skills require to get a job role as data analyst. This certification also helps in getting an internship or entry-level jobs in different organizations and firms. The average salary of a certified R programmer with this certification is ₹ 508,224 per annum.Top companies and industries hiring certified R programmers are Technovatrix, CGI Group Inc., Amazon, Sparx IT Solutions, Accenture, Uber, etc.Where to take Training for Certification: KnowledgeHut has a fascinating training course for those who wants to become a R programmer. It has 22+ hours of instructor-led live training and three self-paced live projects.Who should take the Training (roles) for Certification: Any data analyst, graduate, post graduate student, experienced data analyst or computer science aspirant - who wants to settle as a R programmer or data analyst can opt for this certification course. There is no other prerequisite to appear for this exam.Course fees for Certification:FreeFee for certification:$ 60 (Coursera Plus Monthly)Retake fee for certification: Free6. Oracle MySQL Database Administration Training and Certification (CMDBA)It is another course offered by Oracle for SQL developers. Oracle University designed this course for database administrators who want to validate their skills with developing performance, blending business processes, and accomplishing data processing work. Structured Query Language (SQL) is one of the top database management query languages that allows us to access and manipulate databases. If you want to verify your database skills during a job interview or impress your peers at your workplace then this certification is worth getting. This certification path includes Professional, Specialist, and Developer levels. The candidate should pass the MySQL Database Administrator Certified Professional Exam Part 1 & Part 2 to earn the certification.It comprises of topics likeInstalling MySQLMySQL ArchitectureConfiguring MySQLUser ManagementMySQL SecurityMaintaining a Stable SystemOptimizing Query PerformanceBackup StrategiesConfiguring a Replication TopologyDemand and Benefits: Having an CMDBA certification verifies that the programmer or the aspirant has all the necessary and essential skills required to get a job role as SQL developer. This certification also helps in getting an internship or entry-level jobs in different organizations and firms. The average salary of a certified MySQL DBA or backend developer with this certification is $ 66,470 per annum.Top companies and industries hiring Certified MySQL database administrators are Fiserv, IBM, HCL, Adobe, Microsoft, Apple, Accenture, Collabera, and more.Where to take Training for Certification: KnowledgeHut has a cutting-edge curriculum for those who want to become MySQL database administrators. It has 16+ hours of instructor-led online lectures and 80+ hours of hands-on lab. Apart from that, this self-paced course has Capstone projects.Who should take the Training (roles) for Certification: Any developer, graduate, post graduate student, experienced developer or computer science aspirant - who wants to pursue a career as a DBA or backend developer or start his/her career in database management or backend software development can opt for this certification course. There is no other prerequisite to appear for this exam or course.Course fees for Certification:$ 255Exam fee for certification:$ 255Retake fee for certification: Aspirants can retake the exam if the exam voucher has a free retake option. If the exam retake option is available, one can opt for the exam after 14 days after the initial attempt.7. CCA Spark and Hadoop DeveloperWith the exponential growth in data, IT firms and organizations have to manage this tremendous amount of data generated. So, many companies are actively looking for Big data and Spark developers who can optimize performance. Big Data is the term used to describe enormous volumes of data. Apache Spark supports data management as it is an open-source centralized analytics engine that handles large-scale data processing.It requires prerequisite knowledge of Scala and Python. This certification also verifies and showcases your skills through Spark and Hadoop projects. Passing this certification course gives you a logo and a license to authenticate your CCA status.It comprises of topics likeLoad data from HDFS for use in Spark applicationsWrite the results back into HDFS using SparkRead and write files in a variety of file formatsPerform standard extract, transform, load (ETL) processes on data using the Spark APIUse metastore tables as an input source or an output sink for Spark applicationsUnderstand the fundamentals of querying datasets in SparkFilter data using SparkWrite queries that calculate aggregate statisticsJoin disparate datasets using SparkProduce ranked or sorted dataSupply command-line options to change your application configuration, such as increasing available memoryDemand and Benefits: Passing the CCA Spark and Hadoop Developer Exam (CCA175) by Cloudera verifies that you have all the essential skills required to get a job as a Hadoop developer and handle Big data projects. The average salary of a certified CCA Spark and Hadoop Developer with this certification is $ 74,200 per annum.Top companies and industries hiring Certified Spark and Hadoop Developers are Primus Global, IBM, Collabera, CorroHealth, Genpact, Xerox, Accenture, and more.Where to take Training for Certification: KnowledgeHut has extensive courses for those who want to become Big Data experts and want to work as Hadoop developers. It has different courses on Big Data Analytics, Apache Storm, Hadoop Administration, Apache Spark & Scala, Big Data with Hadoop, and more.Who should take the Training (roles) for Certification: Any Big Data developer, graduate & post graduate students, Hadoop developer or computer science aspirant - who wants to make a career in Big data development or start his/her career as a Big Data or Hadoop project developer can opt for this certification course. There is no other prerequisite to appear for this exam.Course fees for Certification:$ 295Application fee for certification:$ 295Exam fee for certification:$ 295Retake fee for certification: Within 30 to 60 minutes of exam completion, Cloudera will send a scorecard mail with a pass or fail status. If the candidate fails the exam, then they have to wait for 30 days for another try. Cloudera gives additional discounts on retakes.ConclusionWhether you are starting your career as a coder or are an experienced programmer looking to grow in the industry, having a certification and proper knowledge of any popular programming language is one of the most proven ways to elevate your programming career. We trust that this article will help you to understand your area of interest. Choose the programming language you wish to make a career in, wisely. This would also depend on your pre-existing knowledge. If you aren't sure which resource will be more informative for doing your certification as per your area of interest, KnowledgeHut (//www.knowledgehut.com/) has all the support and expert trainers who can guide you, from start to finish—that is in clearing the exam and helping you gain sound knowledge of your preferred subject.Receiving a programming certification is an added bonus which will make you stand out from the rest. Proper training from an institute such as KnowledgeHut will help you gain skills that are relevant and in demand in the industry.

Video liên quan

Postingan terbaru

LIHAT SEMUA