I am learing comprehension and i can't figure out how to run a for loop a N amount of times. In this case I want to import the first 5 lines of a .csv file. But I want to understand the logic for further solutions.
def columnMatch(self): with open(self.file_path) as csvfile: readcsv = csv.reader(csvfile, delimiter=';') line_count = 0 row_list = [] for row in readcsv: if line_count < 5: row_list.append(row) line_count += 1 return row_list
breakthe loop once the criteria is exceeded.from itertools import isliceandfor row in islice(readcsv, 5):limits the loop to 5 iterations.row_list = list(islice(readcsv, 5)); no need to use a list comprehension when all the list comprehension does is echo the loop target. :-) (rowis the loop target in your loop).