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

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • difference between positional and keyword arguments

    1. Positional Arguments How they work: The arguments you pass are matched to the function’s parameters based solely on their order (i.e., their position). The first argument is assigned to the first parameter, the second to the second, and so on. Example: python def describe_pet(animal_type, pet_name): “””Display information about a pet.””” print(f”\nI have a {animal_type}.”) print(f”My {animal_type}’s name…

Leave a Reply

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