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 to slice a nested list twice?

With a nested list like:

ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I need to be able to slice this list for:

[[1, 2], [4, 5]]

I’ve been trying:

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

list(ex_list[:2][:2])

but this isn’t working. I’m obviously doing something very wrong but haven’t been able to find a solution as using commas doesn’t work either for some reason.

>Solution :

You should try using comprehension:
Try:

[i[:2] for i in ex_list[:2]]

Code:

ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([i[:2] for i in ex_list[:2]])

Output:

[[1, 2], [4, 5]]
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