What does the append() method do in a Python list?
a) Adds an item to the end of the list
b) Removes an item from the list
c) Sorts the list in ascending order
d) Reverses the order of items in the list
Answer:
a) Adds an item to the end of the list
Explanation:
The append()
method in Python adds a new item to the end of an existing list. This method is commonly used to dynamically build up a list by adding elements one at a time.
# Example of append() method
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
In this example, the number 4
is added to the end of the list numbers
using the append()
method.
Using append()
is a straightforward way to add new items to a list without modifying the existing elements or their order.