Create a new list from the namedtuple attribute

I am trying to copy the names of books that are <2000 to a new list. But the problem is that it only copies “1984” and copies it as a separate character to the list, and does not copy all the names that it should have

from collections import namedtuple
Book = namedtuple('Book','author title genre year price instock')

BSI = [ Book('John Green', 'Paper Towns', 'Young Adult', 2008, 7.00, 200),
        Book('Beverly Clearly', 'Ramona Forever', 'Children', 1924, 9.00, 150),
        Book('Vladmir Nabokov', 'Lolita', 'Tragicomedy', 1958, 15.00 , 80),
        Book('J.D. Salinger', 'Catcher in the Rye', 'Young Adult', 1951, 10.00, 130),
        Book('George Orwell', '1984', 'Dystopia', 1949, 7.00, 300),
        Book('Jeannette Walls','The Glass Castle','Memoir', 2006, 15.00 , 100)]

older_books = []

for books in BSI:
    if (books.year<2000):
        older_books=list(books.title)

print(older_books) #Outputs ['1', '9', '8', '4']

What should he infer

Ramona Forever
Lolita
Catcher in the Rye
1984

+4
source share
1 answer

With each cycle, the forcode rewrites the list older_bookswith the last title of the book (converted to a list), because you are not adding it, but simply creating a new list each time.

>>> list('Ramona Forever')
['R', 'a', 'm', 'o', 'n', 'a', ' ', 'F', 'o', 'r', 'e', 'v', 'e', 'r']
>>> list('1984')
['1', '9', '8', '4']

list.append, , , :

>>> older_books = []
>>> older_books.append('Ramona Forever')
>>> older_books.append('1984')
>>> older_books
['Ramona Forever', '1984']

for books in BSI:
    if books.year < 2000:
        older_books.append(books.title)  # <---

:

older_books = [b.title for b in BSI if b.year < 2000]
+3

Source: https://habr.com/ru/post/1612027/


All Articles