# Need help with understanding

Code:

``````from csv import reader

opened_file = open(csv_filename)
rows = []
if num_rows == 0 or len(rows) + 1 <= num_rows:
rows.append(row)
return rows
``````

I need help understanding what’s going on inside the for loop. Specifically the second part of the if statement (after the “or”).

hey @bouahth2018

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.

4 Likes

@Rucha Thanks for clearing that up! Much appreciated.

2 Likes

@Rucha Oh man, this is one of the best explanation! Love it

1 Like

It’s Woman! Thanks!

2 Likes

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?

1 Like

@ 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 `read_file`.

1 Like