Slicing lists imported from CSV files
I have a list of 156 elements (all integers) in a CSV file. I'm importing the list using the following code:
with open("rayuela-chapter-list.txt") as f: r = csv.reader(f) x = [row for row in r]
When I try to slice the list I get the errors like the one below:
x Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
When it does not give me an error it returns the entire list, no matter how I slice it.
If I'm importing a CSV file, how do I make sure that I can slice the resulting list? is there anything I'm missing in the code?
If the list is stored in csv as a row, you are reading this whole row in one take. Basically, this line
x = [row for row in r]
If there would be more rows, it would be a list of lists, but in your case, it is a list of one list. To get what you need, just do:
x = x