Python Coding Day 10 | Python List : insert, remove, pop, clear

Python List : insert, remove, pop, clear

Watch the lesson tutorial  ðŸ”»


Python lists are one of the most versatile and important data structures, allowing you to store an ordered, mutable sequence of items. These methods demonstrate how to add, remove, and manage elements within a list.

1. list.insert(i, x): Adding an Item by Index

The insert() method adds an item $x$ at a specified $i$ndex position. This shifts all subsequent elements to the right.

  • $i$: The index where you want to insert the item.

  • $x$: The item you want to insert.

Practical Example Code

This example inserts the number 5 at index 0 (the beginning) of the list.

Python
list_to_insert = [10, 20, 30]
print(f"Original List: {list_to_insert}")

# Insert '5' at index 0
list_to_insert.insert(0, 5)

print(f"List after insert(0, 5): {list_to_insert}")
# Output: [5, 10, 20, 30]

2. list.remove(x): Removing the First Occurrence of a Value

The remove() method searches the list for the first occurrence of the specified item $x$ and deletes it.

  • $x$: The item whose value you want to remove.

  • Note: If the item $x$ is not found, a ValueError is raised. If duplicates exist, only the first one found is removed.

Practical Example Code

This list contains two 20s, but remove(20) deletes only the first one it encounters.

Python
list_to_remove = [10, 20, 30, 20]
print(f"Original List: {list_to_remove}")

# Remove the first instance of '20'
list_to_remove.remove(20)

print(f"List after remove(20): {list_to_remove}")
# Output: [10, 30, 20] (The second '20' remains)

3. list.pop(i): Removing an Item by Index and Retrieving Its Value

The pop() method is unique because it performs two actions:

  1. It removes the item at the specified $i$ndex.

  2. It returns the removed item's value.

  • $i$: The index of the item you want to remove. If no index is specified, pop() removes and returns the last item.

Practical Example Code

This example removes the item at index 1 (20) and stores its value in the variable x.

Python
list_to_pop = [10, 20, 30, 20]
print(f"Original List: {list_to_pop}")

# Remove the item at index 1 (which is 20)
x = list_to_pop.pop(1)

print(f"Value popped (x): {x}")
# Output: 20

print(f"List after pop(1): {list_to_pop}")
# Output: [10, 30, 20]

4. list.clear(): Emptying the Entire List

The clear() method removes all items from the list, making it an empty list ([]).

Practical Example Code

Python
list_to_clear = [10, 20, 30, 20]
print(f"Original List: {list_to_clear}")

# Remove all items from the list
list_to_clear.clear()

print(f"List after clear(): {list_to_clear}")
# Output: []

- by Chirana Nimnaka

Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python