Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample code for the article on removing items from list #619

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading