Take the 2-minute tour ×

I am new to Python, so apologies if this seems extremely simple:

I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as strings. What I want to do is loop through the list (which can be a variable number of rows) and convert the index 2 string to a float. I run the following code, but when i print the list, everything is still a string:

import csv

def main():
    benchmark = list(csv.reader(open('test.csv', 'r')))

    for i in range((len(benchmark))):
        benchmark[i][2] = float(benchmark[i][2])

Any help would be much appreciated.


share|improve this question
That code works for me. –  interjay Oct 6 '11 at 16:40
Since this code is correct, you will need to post a complete example, including the input data and how you check if the value is still a string. –  interjay Oct 6 '11 at 16:48
add comment

2 Answers

up vote 0 down vote accepted

This would probably work, but I can't test without test data.

>>> benchmark = [[1, 2, 3, 4], [5, 6, 7, 8]]
>>> [[float(col) if i == 2 else col for i, col in enumerate(row)] for row in benchmark]
[[1, 2, 3.0, 4], [5, 6, 7.0, 8]]
share|improve this answer
This is exactly what I was looking for, thanks so much. –  donopj2 Oct 6 '11 at 16:40
add comment

It's not necessary to cast your csv.reader to a list as it is already iterable. You can do something like the following:

with open('test.csv','r') as inp:
    for row in csvin:
        benchmark.append(row[:1] + [float(row[1])] + row[2:])
share|improve this answer
This will convert the second character of each column to a float, probably not what you want. Even if you fix that, the original code seems clearer to me. –  interjay Oct 6 '11 at 16:46
@interjay You're right, thanks! Was a bit overzealous there with the map/lambda. –  Austin Marshall Oct 6 '11 at 16:55
add comment

Your Answer


