Screen Link: https://app.dataquest.io/m/1013/functions%3A-intermediate-practice-problems/5/reading-a-partial-csv
from csv import reader
def read_partial_csv(csv_filename, num_rows=0):
opened_file = open(csv_filename)
read_file = reader(opened_file)
rows = 
for row in read_file:
if num_rows == 0 or len(rows) + 1 <= num_rows:
I need help understanding what’s going on inside the for loop. Specifically the second part of the if statement (after the “or”).
Welcome to the DQ community! Glad to have you here.
len(rows) will give you the length of rows list declared/created just above the for loop.
len(rows) + 1 will add 1 to the len so, if
len(rows) = 0 then
0 + 1 = 1, if
len(rows) = 3 then
3 + 1 = 4.
Now we check whether
len(row) + 1 <= num_rows. where num_rows will be provided as input.
Say, num_rows = 5, then:
1st loop: len(rows) = 0 >>
0 +1 <= 5? Yes 1 is less than 5. So append the first row from read_file to the rows List.
2nd loop: len(rows) = 1 >>
1 + 1 <= 5? Yes 2 is less than 5. So append the second row from read_file to rows List
5th loop: len(rows) = 4 >>
4 + 1 <= 5? Yes 5 is equal to 5. So append the fifth row from read_file to rows List.
6th loop: len(rows) = 5 >>
5 + 1 <= 5? No. 6 > 5. So the loop will stop here.
And we will have the first 5 rows (index 0 to 4) from read_file in rows List.
Hope this helps you. Let us know in case otherwise.
@Rucha Thanks for clearing that up! Much appreciated.
@Rucha Oh man, this is one of the best explanation! Love it
I don’t understand how the python knows that we have to use particular rows that are posted in “if” statement. Are there some invisible brackets for line/column(indexing/sliceing) somwhere? Where is the link?
@ drill_n_bass Drill N Bass
There is no hiding slicing or indexing, I’m requesting you to explore the explanation that @ Rucha Ruchi Sharma gave.
It’s just keeps checking length of the list
rows as well as keeps appending(inserting) one row each time to the list
rows(that was initially empty) and does this job until the length of rows is matched with your given argument, say
numrows = 5. And otherwise your default argument
numrows == 0, for this the loop continues to append rows until you finish appending all rows of your