Monday, January 6, 2025
HomeProgrammingHow to Remove Item from a List in Python

How to Remove Item from a List in Python

  1. Using remove(): Removes the first occurrence of the value.
    python
    my_list = [1, 2, 3, 4]
    my_list.remove(3)
    print(my_list) # [1, 2, 4]
  2. Using pop(): Removes an item by index.
    python
    my_list = [1, 2, 3, 4]
    my_list.pop(2)
    print(my_list) # [1, 2, 4]
  3. Using del: Deletes an item by index or slices.
    python
    my_list = [1, 2, 3, 4]
    del my_list[1]
    print(my_list) # [1, 3, 4]
  4. Using List Comprehension: To remove multiple occurrences.
    python
    my_list = [1, 2, 3, 4, 2]
    my_list = [x for x in my_list if x != 2]
    print(my_list) # [1, 3, 4]
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x