Computer Science
What are the two ways to add something to a list ? How are they different ?
Python List Manipulation
3 Likes
Answer
The two methods to add something to a list are:
append method — The syntax of append method is
list.append(item)
.extend method — The syntax of extend method is
list.extend(<list>)
.
Difference
The difference between the append() and extend() methods in python is that append() adds one element at the end of a list, while extend() can add multiple elements, given in the form of a list, to a list.
Example
append method:
lst1 = [10, 12, 14]
lst1.append(16)
print(lst1)
Output — [10, 12, 14, 16]
extend method:
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
Output — ['a', 'b', 'c', 'd', 'e']
Answered By
2 Likes
Related Questions
Start with the list [8, 9, 10]. Do the following using list functions:
- Set the second entry (index 1) to 17
- Add 4, 5 and 6 to the end of the list
- Remove the first entry from the list
- Sort the list
- Double the list
- Insert 25 at index 3
What's a[1 : 1] if a is a string of at least two characters ? And what if string is shorter ?
What are the two ways to remove something from a list? How are they different ?
What is the difference between a list and a tuple ?