Computer Science
What are the two ways to remove something from a list? How are they different ?
Python List Manipulation
2 Likes
Answer
The two ways to remove something from a list are:
pop method — The syntax of pop method is
List.pop(<index>)
.del statement — The syntax of del statement is
del list[<index>] # to remove element at index
del list[<start>:<stop>] # to remove elements in list slice
Difference
The difference between the pop() and del is that pop() method is used to remove single item from the list, not list slices whereas del statement is used to remove an individual item, or to remove all items identified by a slice.
Example
pop() method:
t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']
ele1 = t1.pop(0)
print(ele1)
Output — 'k'
del statement:
lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)
Output — [1, 2, 5]
Answered By
2 Likes
Related Questions
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 add something to a list ? How are they different ?
What is the difference between a list and a tuple ?
In the Python shell, do the following :
- Define a variable named states that is an empty list.
- Add 'Delhi' to the list.
- Now add 'Punjab' to the end of the list.
- Define a variable states2 that is initialized with 'Rajasthan', 'Gujarat', and 'Kerala'.
- Add 'Odisha' to the beginning of the list states2.
- Add 'Tripura' so that it is the third state in the list states2.
- Add 'Haryana' to the list states2 so that it appears before 'Gujarat'. Do this as if you DO NOT KNOW where 'Gujarat' is in the list. Hint. See what states2.index("Rajasthan") does. What can you conclude about what listname.index(item) does ?
- Remove the 5th state from the list states2 and print that state's name.