Differentiate between append() and extend() functions of list.
Question
Differentiate between append() and extend() functions of list.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
The append()
and extend()
functions in Python lists serve different purposes:
append():
Purpose: Adds a single element to the end of the list.
Effect: The added element can be of any data type, including another list.
Example:
list1 = [1, 2, 3] list1.append(4) # Output: [1, 2, 3, 4] list1.append([5, 6]) # Output: [1, 2, 3, 4, [5, 6]]
extend():
Purpose: Adds each element of an iterable (e.g., list, tuple) to the end of the list.
Effect: The elements of the iterable are added individually.
Example:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) # Output: [1, 2, 3, 4, 5, 6]
In summary, append()
adds its argument as a single element to the list, while extend()
iterates over its argument adding each element individually to the list.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month