Explain append and extend method with example
Question
Explain append and extend method with example
Solution
Sure, I'd be happy to explain the append and extend methods in Python.
- Append Method: The append() method in Python adds a single item to the existing list. It doesn't return a new list; rather it modifies the original list.
Example:
# create a list
list1 = ['apple', 'banana', 'cherry']
print("Original List:", list1)
# append 'orange' to the list
list1.append('orange')
print("Updated List:", list1)
Output:
Original List: ['apple', 'banana', 'cherry']
Updated List: ['apple', 'banana', 'cherry', 'orange']
In this example, 'orange' is added to the end of list1.
- Extend Method: The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list. Here, the iterable is not a single element, but all the elements of iterable are added to the list.
Example:
# create two lists
list1 = ['apple', 'banana', 'cherry']
list2 = ['orange', 'grape']
print("Original List1:", list1)
print("Original List2:", list2)
# extend list1 with list2
list1.extend(list2)
print("Updated List1:", list1)
Output:
Original List1: ['apple', 'banana', 'cherry']
Original List2: ['orange', 'grape']
Updated List1: ['apple', 'banana', 'cherry', 'orange', 'grape']
In this example, all elements of list2 are added to the end of list1.
Similar Questions
What’s the Difference Between the Python append() and extend() Methods?
Which of the following methods is used to append an element to the end of an array in Python?Optionsappend()add()extend()insert()
Which method adds an element to the end of a list?Answer areaappend()add()insert()extend()
Explain Method overriding with example?
Explain method Overloading
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.