Open In App
Related Articles

Read a CSV into list of lists in Python

Improve Article
Save Article
Like Article

In this article, we are going to see how to read CSV files into a list of lists in Python.

Method 1: Using CSV module

  • We can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.
  • We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV contents to list with or without headers.

Example 1:

In this example, we are reading a CSV file and converting the string into the list.



import csv
with open('sample.csv', 'r') as read_obj:
    # Return a reader object which will
    # iterate over lines in the given csvfile
    csv_reader = csv.reader(read_obj)
    # convert string to list
    list_of_csv = list(csv_reader)


[[‘JAN’, 34, 360, 417], [‘FEB’, 31, 342, 391], [‘MAR’, 36, 406, 419], [‘APR’, 34, 396, 461],

 [‘MAY’, 36, 420, 472], [‘JUN’, 43, 472, 535], [‘JUL’, 49, 548, 622], [‘AUG’, 50, 559, 606], 

 [‘SEP’, 40, 463, 508], [‘OCT’, 35, 407, 461], [‘NOV’, 31, 362, 390], [‘DEC’, 33, 405, 432]]

Example 2:

In this example, we are reading a CSV file and iterating over lines in the given CSV.



import csv
with open('example.csv') as csvfile:
    # Return a reader object which will
    # iterate over lines in the given csvfile.
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row[0], row[1], row[2],)



Method 2: Using Pandas

You can use the pandas library for this which has an inbuilt method to convert values to a list. Pandas.values property is used to get a numpy.array and then use the tolist() function to convert that array to list.

Note: For more information refer Read CSV Into List Using Pandas


import pandas as pd
# Creating Dictionary
dict = {
    'series': ['Friends', 'Money Heist', 'Marvel'],
    'episodes': [200, 50, 45],
    'actors': [' David Crane', 'Alvaro', 'Stan Lee']
# Creating Dataframe
df = pd.DataFrame(dict)



Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 08 Apr, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials