The append() and extend() methods are both used to add items to a list in Python. However, they work slightly differently.
The append() method adds a single item to the end of a list. Here's an example:
# Define a list my_list = [1, 2, 3] # Use the append() method to add an item to the end of the list my_list.append(4) # Print the list print(my_list)This will print [1, 2, 3, 4], showing that the number 4 has been added to the end of the list.
On the other hand, the extend() method adds all the items from one list to the end of another list. Here's an example:
# Define two lists list1 = [1, 2, 3] list2 = [4, 5, 6] # Use the extend() method to add the items from list2 to the end of list1 list1.extend(list2) # Print the list print(list1)
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.