Skip to main content

Removing elements from a list in Python with list method pop()

Removing elements from a list

It's often essential to remove the data from any data set (let's take 'list' in this case). 

The list method "pop()" comes handy in this case, this method allows removing the last element of a list and return the same. This is a very useful method for amending lists by removing it's elements and can be used in a variety of situations as required.

Using "pop()" to remove the last element from a list

By default "pop()" method removes the last element from a list and returns the same. 

One thing to note here is, it modifies the original list. 

1

2

3

4

5

numbers = [1, 2, 3, 4]

removed_element = numbers.pop()

print(removed_element) # 4

print(numbers) # [1, 2, 3]

 


In the above example, 
  • pop() method removes the last element (i.e., "4" in this case) from the list "numbers". 
  • Returns the removed element, in this case returned element is stored in "removed_element". 
  • Original list is modified to only contain the remaining elements. 
One thing to note here is, if we try to remove the elements from an empty list, it'll raise an IndexError.

1

2

3

4

5

numbers = []

removed_element = numbers.pop() # throws error

print(removed_element)

print(numbers)

 


When we run the above code to remove an element from empty list, an error would be throws (see below). 

Traceback (most recent call last):

  File "C:\Users\pradeep.panga\PycharmProjects\pythonProject\pop.py", line 2, in <module>

    removed_element = numbers.pop()

                      ^^^^^^^^^^^^^

IndexError: pop from empty list


It is important to handle such errors when working with "pop()" method to avoid program failure run time. 

This can be done in one of the two ways. 
  • By checking if the list is empty before calling the pop() method. 
  • By using the pop() method inside try-except block and monitor for the IndexError. 

Removing elements from specific positions in a list

When working with data, we do not always want to remove a last element from list. We often need to remove a specific element from the beginning or middle of a list. 

"pop()" can also be used to remove the element from any position. To achieve this, we would need to pass the index position of the element which needs to be removed.

1

2

3

4

5

numbers = [1, 2, 3, 4]

removed_element = numbers.pop(2)

print(removed_element) # 3

print(numbers) # [1, 2, 4]

 


In the above example, 
  • "pop(2)" removed the element "3" from index position "2". 
  • Original list has been amended to remove the corresponding element from the list. 

Using pop() in a loop to remove all elements from a list

In the previous examples, we have seen how to delete a single element from a list. 

We could use the "pop()" method in a while loop to remove all the elements from a list. 

E.g.: 
Removing all elements from a list by using pop() in a while loop. 

1

2

3

4

5

6

7

8

9

numbers = [1, 2, 3, 4]

removed_elements_list = []

while numbers:

   removed_element = numbers.pop()

   removed_elements_list.append(removed_element)

 

print(numbers) # []

print(removed_elements_list) # [4, 3, 2, 1]

 


In the above example, 
  • Line - 3: "while numbers:" - This loop is repeated until the list is empty. So, loop will not run on a empty list and IndexError will not occur. 
  • Lines - 4 & 5: Last element from the list is removed and added to the new list created (i.e., removed_elements_list).
  • Line - 7: Original list (i., numbers) is empty as all the elements were removed. 
  • Line - 8: New list (i.e., removed_elements_list) contain the elements in reverse order to the original list as the elements are removed from the last index and added. 
Using a while loop and pop() method to remove all elements from a list can be an effective approach, especially if the list is large. It avoids the need to create a new list, which can be slower and requires allocation of further system resources.

One thing to remember here is, This would only work if we do not require the original list as the pop() methods removed the element and by the end of the loop, original list would be empty. 

We could also keep a copy of the list if required, before starting to use the pop() method.

Conclusion

In this post, we explored the usage of a list method "pop()" and how to remove the element from the end of a list, any index position of a list and to remove all the elements by using pop() in a loop. 

Hope this has been a bit of help in understanding the use of list method pop() in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i