Learn Python: Files - List Syntax

I’m working with file in Python. The task is

  1. Import the csv module.
  2. Open up the file books.csv in the variable books_csv .
  3. Create a DictReader instance that uses the @ symbol as a delimiter to read books_csv . Save the result in a variable called books_reader .
  4. Create a list called isbn_list , iterate through books_reader to get the ISBN number of every book in the CSV file. Use the ['ISBN'] key for the dictionary objects passed to it.

This is the key answer but I’m not familiar with the syntax at the last line (isbn_list).

import csv
with open("books.csv") as books_csv:
  books_reader = csv.DictReader(books_csv, delimiter="@")
  isbn_list = [book["ISBN"] for book in books_reader]
    

Here is my coding

import csv
with open("books.csv") as books_csv:
  books_reader = csv.DictReader(books_csv, delimiter="@")
  for row in books_reader:
    isbn_list = row["ISBN"]
    print(isbn_list)
    

The output of my coding is different from the answer because it’s not a list, just plain text. But I don’t understand how the last line in the answer key works.

It’s a list comprehension. The lessons haven’t discussed that yet? Is this the Python 3 course or Data Science path?

It loops through each row in the books_reader instance you’ve created to retrieve each book’s ISBN.

It’s a bit more efficient than a regular for loop.

See the documentation here.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.