Reputation: 69
def delete_books(name):
books=list_book()
books=[book for book in books if book['name']==name]
savefile_books(books)
My question is about list comprehension in python. I requested you to explain in detain about this for loop. How its work and how its look in normal code without list comprehension?
Upvotes: 1
Views: 50
Reputation: 1983
This function will do the same as your function, but without list comprehension:
def delete_books_no_list_comprehension(name):
books = list_book()
filtered_books = []
for book in books:
if book['name'] == name:
filtered_books.append(book)
savefile_books(filtered_books)
See also, for more info: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Upvotes: 0
Reputation: 5735
books = [book for book in books if book['name']==name]
it is the same as:
new_books = []
for book in books:
if book['name']==name:
new_books.append(book)
books = new_books
As you see the list comprehension is much more elegant.
Upvotes: 2