pop(), remove(), clear(), and del 

pop()remove()clear(), and del with 5 examples each, including slicing where applicable:


1. pop([index])

Removes and returns the item at the given index. If no index is given, it removes the last item.

Examples:

  1. Remove the last element (default):pythonnums = [1, 2, 3] popped = nums.pop() print(nums) # [1, 2] print(popped) # 3
  2. Remove at a specific index:pythonfruits = [“apple”, “banana”, “cherry”] removed = fruits.pop(1) print(fruits) # [“apple”, “cherry”] print(removed) # “banana”
  3. Using negative index (-1 = last element):pythonletters = [‘a’, ‘b’, ‘c’] letters.pop(-1) # Removes ‘c’ print(letters) # [‘a’, ‘b’]
  4. Using slicing to simulate pop():pythonnums = [10, 20, 30] popped = nums[-1] # Get last element nums = nums[:-1] # Remove last element print(nums) # [10, 20] print(popped) # 30
  5. Error if index is out of range:pythonlst = [1, 2] lst.pop(5) # IndexError: pop index out of range

2. remove(x)

Removes the first occurrence of the specified value x. Raises ValueError if not found.

Examples:

  1. Remove a string:pythonfruits = [“apple”, “banana”, “cherry”] fruits.remove(“banana”) print(fruits) # [“apple”, “cherry”]
  2. Remove a number:pythonnums = [1, 2, 3, 2] nums.remove(2) # Removes first ‘2’ print(nums) # [1, 3, 2]
  3. Error if element doesn’t exist:pythonlst = [1, 2, 3] lst.remove(4) # ValueError: list.remove(x): x not in list
  4. Using slicing + remove():pythonnums = [10, 20, 30, 20] nums = nums[:2] + nums[3:] # Removes nums[2] (30) print(nums) # [10, 20, 20]
  5. Remove all occurrences (using loop):pythonnums = [1, 2, 3, 2, 2] while 2 in nums: nums.remove(2) print(nums) # [1, 3]

3. clear()

Removes all elements from the list, making it empty.

Examples:

  1. Basic usage:pythonnums = [1, 2, 3] nums.clear() print(nums) # []
  2. Using slicing to clear:pythonlst = [10, 20, 30] lst[:] = [] # Same as clear() print(lst) # []
  3. Difference with del:pythonlst1 = [1, 2, 3] lst1.clear() # lst1 = [] (still exists) lst2 = [1, 2, 3] del lst2[:] # Same as clear() print(lst2) # []
  4. Using *= to clear (not recommended):pythonlst = [1, 2, 3] lst *= 0 # Clears the list print(lst) # []
  5. Reassigning vs clear():pythonlst = [1, 2, 3] lst = [] # Creates a new list (old may still exist in memory) lst.clear() # Modifies existing list

4. del Statement

Deletes elements by index or slice (not a method, but a Python keyword).

Examples:

  1. Delete by index:pythonnums = [10, 20, 30] del nums[1] print(nums) # [10, 30]
  2. Delete a slice:pythonlst = [‘a’, ‘b’, ‘c’, ‘d’] del lst[1:3] print(lst) # [‘a’, ‘d’]
  3. Delete the entire list:pythonlst = [1, 2, 3] del lst # Deletes the list completely print(lst) # NameError: name ‘lst’ is not defined
  4. Using del with slicing (similar to clear()):pythonnums = [1, 2, 3] del nums[:] # Clears the list print(nums) # []
  5. Delete every alternate element:pythonnums = [1, 2, 3, 4, 5] del nums[::2] # Removes 1, 3, 5 print(nums) # [2, 4]

Summary Table

MethodModifies List?Removes ByReturns Removed?Error if Missing?
pop([i])✅ YesIndex✅ YesIndexError
remove(x)✅ YesValue❌ NoValueError
clear()✅ YesAll❌ No❌ No
del✅ YesIndex/Slice❌ NoIndexError

Similar Posts

  • Finally Block in Exception Handling in Python

    Finally Block in Exception Handling in Python The finally block in Python exception handling executes regardless of whether an exception occurred or not. It’s always executed, making it perfect for cleanup operations like closing files, database connections, or releasing resources. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else:…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

Leave a Reply

Your email address will not be published. Required fields are marked *