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

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 1:[1]

you could do

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

though the entire file is read into memory

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Ryan