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.
>Solution :
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