Home > Software engineering >  Python - leave only n items in a list
Python - leave only n items in a list

Time:09-02

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.

CodePudding user response:

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

CodePudding user response:

very similar to the solution of ShadowRanger, but using a slice assignment on the left hand side of the assigment oparator:

lst[n:] = []
  • Related