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

Keep two, skip two in Python list

I have a Python list

num_list = list(range(1,33))

And need every other pair of numbers in the list, like this:

[1, 2, 5, 6, 9, 10 ... ]

I’ve figured out how to exclude certain indices from the list, like this

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

num_list[2::3]

> [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

but haven’t figured out how to allow it to capture two indices at a time.

>Solution :

You could use enumerate, then filter the index mathematically:

[v for i, v in enumerate(num_list) if i % 4 < 2]
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