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

Interpreting special case of 'x for x in …' loop in python

I have a question about the code chunk below:

for i, name in enumerate([x[:-3] for x in dm_cov.columns[:10]]):
    stats['beta'][i].write(f'../data/{sub}_beta_{name}.nii.gz')

Is it accurate to say that the above code chunk is functionally equivalent to the code chunk below?

for i, name in enumerate([x for x in dm_cov.columns[:7]]):
    stats['beta'][i].write(f'../data/{sub}_beta_{name}.nii.gz')

I’m curious because x should be a column name, so I’m not sure how it can be subsetted with [:-3].

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

Thank you!

>Solution :

No, the two snippets are not equivalent. dm_cov.columns[:10] gives the first ten column names.

x[:-3] for x in ... then slices out the last three characters of each column name given by dm_cov.columns[:10].

Your second snippet [x for x in dm_cov.columns[:7]] just takes the first seven column names in their entirety.

By the way, that list comprehension is useless in the second snippet, you could just enumerate(dm_cov.columns[:7])

You can verify this by using a different iterable instead of dm_cov.columns:

test = [f"data{i}_col" for i in range(15)]
# ['data0_col', 'data1_col', 'data2_col', 'data3_col', 'data4_col', 'data5_col', 'data6_col', 'data7_col', 'data8_col', 'data9_col', 'data10_col', 'data11_col', 'data12_col', 'data13_col', 'data14_col']

print([x[:-3] for x in test[:10]])
# ['data0_', 'data1_', 'data2_', 'data3_', 'data4_', 'data5_', 'data6_', 'data7_', 'data8_', 'data9_']

print([x for x in test[:7]])
# ['data0_col', 'data1_col', 'data2_col', 'data3_col', 'data4_col', 'data5_col', 'data6_col']
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