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 now

Everything You Need to Know About Let in Javascript

Article

A Guide to Convert String to Int in Javascript

Article

Blockchain Career Guide: A Comprehensive Playbook To Becoming A Blockchain Developer

Ebook

Understanding the NVL Function in SQL

Article

Converting a String to Integer Value With atoi[] Function

Article

Top 60 Java Interview Questions and Answers in 2021

Video Tutorial

Best Programming Languages to Learn in 2022

Article

List to String in Python

Article

Hooks in React JS

Article

AngularJS Vs. Angular 2 Vs. Angular 4: Understanding the Differences

Article

Pop in Python: An Introduction to Pop Function with Examples

By SimplilearnLast updated on Oct 28, 2021820

Table of Contents

View More

List 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.

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 Course

Learn Data Operations in PythonExplore Course

What 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 It

In 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 Python

This article contains more examples to help you better understand the Python list pop[] function.

Example: Using Pop In Python Without Passing Index

In 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 Indices

For 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 Exception

In 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[] Function

The syntax of dictionary pop is:

dictionary.pop[key[, default]]

The parameters are:

  • key: As the dictionary works in a key: value pair, it is the key value to be removed
  • default: The default value is to be returned if the key is not found. It is an optional parameter

What Value Does Dictionary Pop In Python Return?

The Python dictionary pop[] return value is:

  • If it finds the key, it returns the popped value to which the specified key belongs
  • If it does not find the key, it returns the default value
  • If the key is not found and the default is not specified, it returns a KeyError exception

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning

Examples of Python Dictionary Pop[] Function

Lets 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 Present

Continuing 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 Provided

In 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 Exception

In 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 Up

In 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:

NameDatePlace
Python Training12 Mar -3 Apr 2022,
Weekend batch
Your CityView Details

About the Author

Simplilearn

Simplilearn 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.

View More

Recommended Programs

Python 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 Category
Next Article

Understanding All About Index in Python with Examples

By Simplilearn
1135

Recommended Resources

  • Python Interview Guide

    Ebook
  • List to String in Python

    Article
  • All You Need To Know About Python List

    Video Tutorial
  • IT Skills Training Trends: 2020 and 2021

    Ebook
  • Everything You Need to Know About List Comprehension in Python

    Article
  • Everything You Need to Know About Python Arrays

    Video Tutorial
prevNext

© 2009 -2022- Simplilearn Solutions

Follow us!

Refer and Earn

Company

About usCareers In the media Alumni speakContact us

Work with us

Become an instructorBlog as guest

Discover

SkillupResourcesRSS feedSimplilearn Coupons and Discount OffersCity Sitemap

For Businesses

Corporate trainingPartnersDigital Transformation

Learn On the Go!

Get the Android AppGet the iOS App

Trending 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 Course

Trending 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 Course

Trending 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 Course

Trending Resources

Python Tutorial | JavaScript Tutorial | Java Tutorial | Angular Tutorial | Node.js Tutorial | Docker Tutorial | Git Tutorial | Kubernetes Tutorial | Power BI Tutorial | CSS Tutorial
  • Terms of Use
  • Privacy Policy
  • Refund Policy
  • Reschedule Policy
  • © 2009-2022 - Simplilearn Solutions. All Rights Reserved. The certification names are the trademarks of their respective owners.
smpl_2022-02-11
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Video liên quan

Chủ Đề