Home > database >  How can I simplify this line of code using a common for loop rather than list expansion?
How can I simplify this line of code using a common for loop rather than list expansion?

Time:02-06

Take a look at the following piece of code:

def load_data_k(fname: str, yyy_index: int, **selection):
    selection_key_str = list(selection.keys())[0]
    selection_value_int = selection[selection_key_str]
    print(selection_value_int)
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(selection_value_int)]

first please tell me why is it using next(file) here:

lines = [next(file) for _ in range(selection_value_int)]

then please tell me how can I simplify this line using a normal for-loop rather than a list expansion.

CodePudding user response:

This snippet:

lines = [next(file) for _ in range(selection_value_int)]

expands to:

lines = []
for _ in range(selection_value_int):
    lines.append(next(file))

However this doesn't simplify anything.

next(file) uses File object's generator behaviour Thus loads some lines without getting whole file

CodePudding user response:

you could do

with open(fname) as file:
    lines = file.readlines()[:selection_value_int]

though the entire file is read into memory

  •  Tags:  
  • Related