Skip to content

Commit

Permalink
Merge pull request #619 from realpython/how-to-remove-item-from-list-…
Browse files Browse the repository at this point in the history
…python

Sample code for the article on removing items from list
  • Loading branch information
brendaweles authored Dec 17, 2024
2 parents 2ace37c + f604dd2 commit 57344e7
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
3 changes: 3 additions & 0 deletions how-to-remove-item-from-list-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# How to Remove Items From Lists in Python

This folder provides the code examples for the Real Python tutorial [How to Remove Items From Lists in Python](https://realpython.com/how-to-remove-item-from-list-python/).
36 changes: 36 additions & 0 deletions how-to-remove-item-from-list-python/books.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
print(books.pop(0))
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
read_books = []
read = books.pop(0)
read_books.append(read)
print(read_books)
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Wonder", "Jaws", "Jaws"]
del books[2]
print(books)
del books[-1]
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
books.remove("The Hobbit")
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
books.remove("The Two Towers")
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws"]
del books[0:3]
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws", "It"]
del books[-3:-1]
print(books)

books = ["Dragonsbane", "The Hobbit", "Wonder", "Jaws", "It"]
books.clear()
print(books)
35 changes: 35 additions & 0 deletions how-to-remove-item-from-list-python/phone_book.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
phone_numbers = [
"54123",
"54123",
"54123",
"54456",
"54789",
"54789",
]
for phone_number in phone_numbers[:]:
if phone_numbers.count(phone_number) > 1:
phone_numbers.remove(phone_number)
print(phone_numbers)


phone_numbers = [
"54123",
"54123",
"54123",
"54456",
"54789",
"54789",
]
phone_numbers = list(dict.fromkeys(phone_numbers))
print(phone_numbers)

phone_numbers = [
"54123",
"54123",
"54123",
"54456",
"54789",
"54789",
]
set(phone_numbers)
print(phone_numbers)

0 comments on commit 57344e7

Please sign in to comment.