List pop Python
All Courses Log in Software Development Data Science & Business AnalyticsAI & Machine LearningProject ManagementCyber SecurityCloud ComputingDevOpsBusiness and LeadershipQuality ManagementSoftware DevelopmentAgile and ScrumIT Service and ArchitectureDigital MarketingBig DataCareer Fast-trackEnterpriseOther Segments ArticlesEbooksVideo TutorialsOn-demand WebinarsFree Practice Tests HomeResourcesSoftware DevelopmentPop in Python: An Introduction to Pop Function with Examples Trending nowEverything You Need to Know About Let in JavascriptArticleA Guide to Convert String to Int in JavascriptArticleBlockchain Career Guide: A Comprehensive Playbook To Becoming A Blockchain DeveloperEbookUnderstanding the NVL Function in SQLArticleConverting a String to Integer Value With atoi() FunctionArticleTop 60 Java Interview Questions and Answers in 2021Video TutorialBest Programming Languages to Learn in 2022ArticleList to String in PythonArticleHooks in React JSArticleAngularJS Vs. Angular 2 Vs. Angular 4: Understanding the DifferencesArticlePop in Python: An Introduction to Pop Function with ExamplesBy SimplilearnLast updated on Oct 28, 2021820Table of ContentsView MoreList pop in Python is a pre-defined, in-built function that removes an item at the specified index from the list. You can also use pop in Python without mentioning the index value. In such cases, the pop() function will remove the last element of the list. Show
What Is the Syntax of List Pop In Python?The pop() methods syntax is: list_name.pop(index) Parameters: index: The Python pop() function accepts only a single parameter which is the items index to be popped out of the list. It is an optional parameter. If you specify an out-of-range index, then the compiler throws an IndexError exception. Python Training CourseLearn Data Operations in PythonExplore CourseWhat Value Does Pop In Python Return?The list pop in Python returns the popped value, or in other words, the item present at the specified index value. It is simpler to understand this with an example. Example: Use Pop In Python to Remove an Item and Return ItIn this code, you will create a list of fruits and then use the Python list pop() function to remove an item at a specified index. You will then store the returned value in a variable and print it to see what the pop() function returns. # Cars list cars = ['Mercedes Benz', 'BMW', 'Jeep', 'Mahindra', 'Maserati'] print(cars) # Using pop() and storing the return value ret_val = cars.pop(2) print('The return value is:', ret_val) # Updated List print('The updated list is:', cars) Output: As you can see in the output, pop in Python returns the popped item. You can also print the return value by merely printing the pop code, instead of storing it in a separate variable, like this: # Cars list cars = ['Mercedes Benz', 'BMW', 'Jeep', 'Mahindra', 'Maserati'] print(cars) # Using pop() and printing the return value print ("The return value is:", cars.pop(2)) # Updated List print('The updated list is:', cars) Output: Note: The pop() function removes the third item from the list as the indexing starts with 0. So when you pass 2 as the argument, it will remove the third item. More Examples For List Pop In PythonThis article contains more examples to help you better understand the Python list pop() function. Example: Using Pop In Python Without Passing IndexIn this code, you will use the same car list. But this time, you wont pass the index argument. # Cars list cars = ['Mercedes Benz', 'BMW', 'Jeep', 'Mahindra', 'Maserati'] print(cars) print ("The return value is:", cars.pop()) # Updated List print('The updated list is:', cars) Output: As you can see in the above output, when you dont pass an index value, the list pop() function by default removes the last item in the list. Example: Using the Python List Pop() Function With Negative IndicesFor this example, you will pass negative index values and see what happens to the car list. # Cars list cars = ['Mercedes Benz', 'BMW', 'Jeep', 'Mahindra', 'Maserati'] print(cars) print ("The return value is:", cars.pop(-2)) # Updated List print('The updated list is:', cars) print ("The return value is:", cars.pop(-1)) # Updated List print('The updated list is:', cars) Output: As you can see from the output, if you pass negative indices, the pop in Python will start counting from the right. But this time, it wont start from 0 and then -1; it will directly begin from -1. Example: Using Out-of-Range Value to Get IndexError ExceptionIn the below program, you will pass an argument larger than the range to get an IndexError exception in the output. # Cars list cars = ['Mercedes Benz', 'BMW', 'Jeep', 'Mahindra', 'Maserati'] print(cars) print ("The return value is:", cars.pop(8)) # Updated List print('The updated list is:', cars) Output: What Is Python Dictionary Pop?Like the list pop in Python, the dictionary pop() function removes an element mentioned at the specified index value from a dictionary. The Syntax of the Python Dictionary Pop() FunctionThe syntax of dictionary pop is: dictionary.pop(key[, default]) The parameters are:
What Value Does Dictionary Pop In Python Return?The Python dictionary pop() return value is:
FREE Data Science With Python CourseStart Learning Data Science with Python for FREEStart LearningExamples of Python Dictionary Pop() FunctionLets look at different examples to understand the functioning of dictionary pop and its value in different scenarios. Example: Using Dictionary Pop In Python when the Key Is PresentContinuing with the cars, you will create a key: value pair for each vehicle to define a dictionary and then use the pop() function to remove one of the items. # Cars Dictionary cars = {'Mercedes Benz': 1, 'BMW': 2, 'Jeep': 3, 'Mahindra': 4, 'Maserati': 5} print(cars) print ("The return value is:", cars.pop('Mahindra')) # Updated Dictionary print('The updated dictionary is:', cars) Output: Example: Using the Python Dictionary Pop() Function When Default Value Is ProvidedIn the below code, you will pass a key that is not present in the dictionary. But you will also give a default value so that the pop() function can return the default value. # Cars Dictionary cars = {'Mercedes Benz': 1, 'BMW': 2, 'Jeep': 3, 'Mahindra': 4, 'Maserati': 5} print(cars) x = cars.pop('Ferrari', 'Lamborghini') print('The popped element is:', x) print('The dictionary is:', cars) Output: As you can see in the output, since the key Ferrari is not present in the dictionary, it returns the default value, Lamborghini. Example: Using Dictionary Pop in Python To Get Keyerror ExceptionIn the below code, you will pass the key that is not present in the dictionary. But this time, you will not give a default value. Thus, the compiler will return a KeyError Exception. # Cars Dictionary cars = {'Mercedes Benz': 1, 'BMW': 2, 'Jeep': 3, 'Mahindra': 4, 'Maserati': 5} print(cars) print(cars.pop('Ferrari')) Output: As the Ferrari key is not present in the dictionary and you have passed no default parameter, it throws the KeyError Exception. Looking forward to making a move to the programming field? Take up thePython Training Courseand begin your career as a professional Python programmer Summing it UpIn this article, you learned about pop in Python, its uses, and its two variants: list pop() and dictionary pop(). It is an essential function in Python. You can learn more about functions basics here. Further, if you want to understand other basic concepts in Python, you can refer to Simplilearns Introduction to Python Basics. The article is a compilation of all the basic concepts of the Python programming language. You can also opt for our Online Python Certification Course if you want to excel in the Python development field. The course has several hours of applied learning resources to help you understand both the basic and advanced Python concepts. Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same as soon as possible. Happy learning! Find our Python Training Online Classroom training classes in top cities:
About the AuthorSimplilearn is one of the worlds leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies. Recommended ProgramsPython Training 4395 Learners Lifetime Access* Post Graduate Program in Data Science 3472 Learners Lifetime Access* *Lifetime access to high-quality, self-paced e-learning content. Explore CategoryUnderstanding All About Index in Python with ExamplesBy Simplilearn1135 Recommended Resources
prevNext © 2009 -2022- Simplilearn Solutions Follow us! Refer and EarnCompany About usCareers In the media Alumni speakContact usWork with us Become an instructorBlog as guestDiscover SkillupResourcesRSS feedSimplilearn Coupons and Discount OffersCity SitemapFor Businesses Corporate trainingPartnersDigital TransformationLearn On the Go! Get the Android AppGet the iOS AppTrending Post Graduate Programs Project Management Certification Course | Cyber Security Certification Course | Data Science Bootcamp Program | Data Analytics Bootcamp Program | Business Analysis Certification Course | Digital Marketing Certification Program | Lean Six Sigma Certification Course | DevOps Certification Course | Cloud Computing Certification Course | Data Engineering Course | AI and Machine Learning Course | Full Stack Web Development CourseTrending Master Programs PMP Plus Certification Training Course | Big Data Engineer Course | Data Science Certification Course | Data Analyst Certification Course | Artificial Intelligence Course | Cloud Architect Certification Training Course | DevOps Engineer Certification Training Course | Advanced Digital Marketing Course | Cyber Security Expert Course | MEAN Stack Developer CourseTrending Courses PMP Certification Training Course | Big Data Hadoop Certification Training Course | Data Science with Python Certification Course | Machine Learning Certification Course | AWS Solutions Architect Certification Training Course | CISSP Certification Training | Certified ScrumMaster (CSM) Certification Training | ITIL 4 Foundation Certification Training Course | Java Certification Course | Python Certification Training CourseTrending Resources Python Tutorial | JavaScript Tutorial | Java Tutorial | Angular Tutorial | Node.js Tutorial | Docker Tutorial | Git Tutorial | Kubernetes Tutorial | Power BI Tutorial | CSS Tutorial
smpl_2022-02-11
|