diff --git a/how-to-remove-item-from-list-python/README.md b/how-to-remove-item-from-list-python/README.md new file mode 100644 index 0000000000..ac19483374 --- /dev/null +++ b/how-to-remove-item-from-list-python/README.md @@ -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/). \ No newline at end of file diff --git a/how-to-remove-item-from-list-python/books.py b/how-to-remove-item-from-list-python/books.py new file mode 100644 index 0000000000..fd33651916 --- /dev/null +++ b/how-to-remove-item-from-list-python/books.py @@ -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) diff --git a/how-to-remove-item-from-list-python/phone_book.py b/how-to-remove-item-from-list-python/phone_book.py new file mode 100644 index 0000000000..5d38291b35 --- /dev/null +++ b/how-to-remove-item-from-list-python/phone_book.py @@ -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)