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

  • Dynamically Typed vs. Statically Typed Languages 🔄↔️

    Dynamically Typed vs. Statically Typed Languages 🔄↔️ Dynamically Typed Languages 🚀 Python Pros: Cons: Statically Typed Languages 🔒 Java Pros: Cons: Key Differences 🆚 Feature Dynamically Typed Statically Typed Type Checking Runtime Compile-time Variable Types Can change during execution Fixed after declaration Error Detection Runtime exceptions Compile-time failures Speed Slower (runtime checks) Faster (optimized binaries)…

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

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

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

Leave a Reply

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