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

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • replace(), join(), split(), rsplit(), and splitlines() methods in Python

    1. replace() Method Purpose: Replaces occurrences of a substring with another substring.Syntax: python string.replace(old, new[, count]) Examples: Example 1: Basic Replacement python text = “Hello World” new_text = text.replace(“World”, “Python”) print(new_text) # Output: “Hello Python” Example 2: Limiting Replacements (count) python text = “apple apple apple” new_text = text.replace(“apple”, “orange”, 2) print(new_text) # Output: “orange orange apple”…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

  • 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…

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

Leave a Reply

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