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

Python – leave only n items in a list

There are many ways to remove n items from the list, but I couldn’t find a way to keep n items.

lst = ["ele1", "ele2", "ele3", "ele4", "ele5", "ele6", "ele7", "ele8", "ele9", "ele10"]
n = 5
lst = lst[:len(lst)-(len(lst)-n)]
print(lst)

So I tried to solve it in the same way as above, but the problem is that the value of ‘lst’ always changes in the work I am trying to do, so that method is not valid.

I want to know how to leave only n elements in a list and remove all elements after that.

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 :

The simplest/fastest solution is:

del lst[n:]

which tells it to delete any elements index n or above (implicitly keeping 0 through n - 1, a total of n elements).

If you must preserve the original list (e.g. maybe you received it as an argument, and it’s poor form to change what they passed you most of the time), you can just reverse the approach (slice out what you want to keep, rather than remove what you want to discard) and do:

truncated = lst[:n]  # You have access to short form and long form

so you have both the long and short form, or if you don’t need the original list anymore, but it might be aliased elsewhere and you want the aliases unmodified:

lst = lst[:n]  # Replaces your local alias, but leaves other aliases unchanged
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