Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading