Pop last element python

Python: Remove last element from a list

This article will discuss different ways to delete the last element from a list in Python.

Table of Contents

Remove the last element from a list in Python using the pop() function

In Python, the list class provides a function pop(index); it accepts an optional argument index and deletes the element at the given index. If no argument is provided, then it, by default, deletes the last element of the list. Let’s use this function to remove the last element from a list,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] # Remove last element from list list_of_num.pop() print(list_of_num)

As we didn’t provide the index argument in the pop() function, therefore it deleted the last item of the list in place.

Frequently Asked:

Remove the last element from a list in Python using slicing

We can slice the list to remove the last element. To slice a list, provide start and end index in the subscript operator. For example,

It will select the elements from index positions start to end-1. If the start index is not provided, it selects from the first element of the list, and if the end index is not provided, it selects until the end of the list.

If the list has N elements, then slice it to select elements from index position 0 to N-1. In the list, we can also select elements using negative indexing, and the index of the last element in the list is -1. So, to delete the last element from a list, select the elements from start to -1. For example,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] # Remove last element from list list_of_num = list_of_num[:-1] print(list_of_num)

It deleted the last element from the list.

Remove the last element from a list in Python using del keyword

To delete the last element from a list, select the last element using negative indexing, and give it to the del keyword to delete it. For example,

list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] # Remove last element from list del list_of_num[-1] print(list_of_num)

It deleted the last item from the list.

Summary

We learned about different ways to delete the last element from a list in Python.

Читайте также:  Search with filters php

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Remove Last Element from List in Python

Remove Last Element from List in Python

Insertion and Deletion are some of the most important operations in any Data Structure. In this article, we are going to focus on the deletion operation of a list. To be more precise we are going to learn how to delete the last element of a list in python. If you don’t know what a list is, you might want to check out our article on deleting the first element in a list.

When it comes to quick storing and manipulating data while programming, Python lists are one of the most commonly utilized sequential data structures. Lists are a type of collection that greatly simplifies the lives of programmers. Removing the last element from a list excludes the last element of a list by shortening the list. For example, if the given list is [1, 2, 3, 4], then the list after the removal of the last element is [1,2,3]. This removal operation reduces the length of the list by one. Let us now look at the methods using which we can remove the last element of a list in Python.

Читайте также:  Maven java home windows

How to Delete the Last Element of a List in Python?

Python provides us with an array of methods, using which we can achieve our target. In this section, we will discuss each of these methods one by one.

1. Using List.pop() method

The List library contains a large number of methods, but the one which we will be using is a method called List.pop(). This method takes one argument, index. The element at the specified position is deleted by this method. However, this argument is optional and if no index is specified then the last element of the list is deleted. The method returns the element which is popped. Note that the result of this operation is inplace, i.e the change takes place in the list itself.

The pop function raises an IndexError, if we try to pop from an empty list.

For example:

# program to delete the last # last element from the list #using pop method list = [1,2,3,4,5] print("Original list: " +str(list)) # call the pop function # ele stores the element #popped (5 in this case) ele= list.pop() # print the updated list print("Updated list: " +str(list))
Original list: [1, 2, 3, 4, 5] Updated list: [1, 2, 3, 4]

2. Using Slicing

Python provides a provision for slicing the lists using the subscript operator. For slicing a list, one needs to provide the starting and ending index in the subscript operator.

The end index is exclusive, i.e. the sublist generated by this method includes elements from the start index until the end-1 index. If the start index is not provided then the elements are selected from the first index of the list. And if no end index is given, then it selects elements until the last index of the list.

We can also provide a negative index, however, in this case, the counting of the indexes starts from the last element. Allow us to elaborate on the last point, the index of the last element of a list is -1, and that of the second last element is -2, and so on. So in order to delete the last element from a list, elements need to be selected from index 0 to -1.

For example:

# program to delete the last # last element from the list #using slicing list = [1,2,3,4,5] print("Original list: " +str(list)) # slice the list # from index 0 to -1 list = list[ : -1] # print the updated list print("Updated list: " +str(list))
Original list: [1, 2, 3, 4, 5] Updated list: [1, 2, 3, 4]

This approach, however, has a major drawback, it generates a copy of the sliced list which needs to be stored in a list variable. Due to this reason, we don’t recommend you use this approach. This method has an advantage as well, this method does not throw an error when applied to an empty list.

Читайте также:  Minifier html with gulp

We know that these concepts are not easy to grasp in one go. Maybe our python tutors can teach you to teach you with 1-on-1 live classes with full focus on your doubts.

3. Using del

Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1. The use of the negative index allows us to delete the last element, even without calculating the length of the list. This decreases the complexity of the program significantly.

You may be wondering how does this approach differ from the List.pop() method? Both the mentioned approaches have one significant difference and similarity between them. Unlike the pop method, the del operator does not return the deleted element. But like the pop method, it raises an IndexError when we try to delete an element from an empty list or specify an index that is greater than the length of the list.

In contrast with the slicing approach, this method does not return the sliced list. This means that the changes are inplace in this approach.

For example:

# program to delete the last # last element from the list #using del list = [1,2,3,4,5] print("Original list: " +str(list)) # call del operator del list[-1] # print the updated list print("Updated list: " +str(list))
Original list: [1, 2, 3, 4, 5] Updated list: [1, 2, 3, 4]

But if you want to delete a variable completely in python, you can do it with the del() method.

Conclusion

Python is known for its easy syntax and English-like commands. Having a strong grasp on the insertion and deletion of operations is a skill that every programmer should possess. In this article, we discussed three approaches, along with their pros and cons, using which we can delete the last element of a list. However, the pop() function is the most recommended and widely accepted method to delete an element from the list.

FavTutor — 24×7 Live Coding Help from Expert Tutors!

About The Author

Riddhima Agarwal

Hey, I am Riddhima Agarwal, a B.tech computer science student and a part-time technical content writer. I have a passion for technology, but more importantly, I love learning. Looking forward to greater opportunities in life. Through my content, I want to enrich curious minds and help them through their coding journey

Источник

Оцените статью