Below are two common functions used in list manipulation in Python:
1. append()
Purpose:
The append() function is used to add a single element to the end of a list. This function
modifies the original list by inserting the new element, and it does not return a new list.
How It Works:
When you call [Link](item), the specified item is added at the end of the list. Since lists
are mutable, the original list gets updated directly.
Example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
In this example, the number 4 is appended to the list my_list, increasing its length by 1.
Key Points:
o It adds only one element at a time.
o It modifies the list in place (does not produce a new list).
2. pop()
Purpose:
The pop() function is used to remove an element from a list by its index and return that
element. If no index is specified, pop() removes and returns the last element in the list.
How It Works:
When you call [Link](index), the function removes the element at the specified index and
returns its value. If you call [Link]() without an index, it defaults to removing the last
element.
Example with an Index:
my_list = [10, 20, 30, 40]
removed_element = my_list.pop(1)
print(removed_element) # Output: 20
print(my_list) # Output: [10, 30, 40]
Here, the element at index 1 (20) is removed from my_list and returned.
Example without an Index:
my_list = ['a', 'b', 'c']
last_element = my_list.pop()
print(last_element) # Output: 'c'
print(my_list) # Output: ['a', 'b']
In this example, the last element ('c') is removed from my_list.
Key Points:
o It removes an element from the list and returns its value.
o Using pop() without an index works well when you need the last element.
o If you use an invalid index, Python raises an IndexError.
These two functions—append() and pop()—are part of Python's built-in list manipulation methods
that help manage dynamic data collections, where you might need to add or remove items as
needed. Let me know if you need more details or further examples!