Skip to content

Instantly share code, notes, and snippets.

@raveensrk
Created August 30, 2023 12:30
Show Gist options
  • Save raveensrk/29170db7a6a12ccfbb6e8e853bac7dce to your computer and use it in GitHub Desktop.
Save raveensrk/29170db7a6a12ccfbb6e8e853bac7dce to your computer and use it in GitHub Desktop.
In python, what is the difference between extend() and append() methods?

Both extend() and append() are methods used to add elements to a list in Python, but they behave differently.

  1. append(): This method is used to add a single element to the end of a list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]
  1. extend(): This method is used to add multiple elements, often from another iterable (like a list or tuple), to the end of the list.
my_list = [1, 2, 3]
other_list = [4, 5, 6]
my_list.extend(other_list)
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]

The key difference lies in the number of elements being added:

  • append() adds a single element, which can be any valid object (including lists, tuples, dictionaries, etc.). If you append a list using append(), the whole list will be treated as a single element in the original list.

  • extend() adds all the elements from an iterable to the list. It essentially unpacks the elements from the iterable and adds them individually to the list.

In your case, since you have a list of dictionaries (new_options), if you want to keep each dictionary as a separate element in the list, you should use extend() or the += operator. If you used append(), the entire new_options list would be treated as a single element in the target list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment