Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

When to use append and when to use add in python?

In Python, append() and add() are methods used to add elements to data
structures, but they are used in different contexts:

1. append():
 append() is a method available for lists in Python.
 It is used to add elements to the end of a list.
 It modifies the original list by adding the specified element.
 Example:
pythonCopy code
my_list = [ 1 , 2 , 3 ] my_list.append( 4 ) print (my_list) # Output: [1, 2,
3, 4]
2. add():
 add() is a method available for sets and some other data
structures in Python.
 It is used to add elements to a set.
 It adds the specified element to the set if it is not already present.
 It does not modify the set if the element is already present (sets
contain only unique elements).
 Example:
pythonCopy code
my_set = { 1 , 2 , 3 } my_set.add( 4 ) print (my_set) # Output: {1, 2, 3, 4}

In summary:

 Use append() when you want to add elements to the end of a list.
 Use add() when you want to add elements to a set, ensuring
uniqueness of elements.
 Additionally, add() is also used for adding elements to collections such
as collections.Counter() and collections.defaultdict(),
but its usage varies depending on the specific data structure.

You might also like