With a list like
lst1 = [2, 3, 4, 5]
I'd like to easily insert a new number 1
at index [0]
, and at the same time drop the 5
at index [-1]
so that I end up with:
[1, 2, 3, 4]
This can be done using:
lst1.insert(0,1)
lst1.pop()
print(lst1)
# output
# [1, 2, 3, 4]
But I'm a bit puzzled by the fact that there does not seem to exist a built-in method to do that directly. The closest thing I've found to a solution is assigning 1
to a list of its own, and then extending it with an indexed lst1
like this:
lst0=[1]
lst0.extend(lst1[:-1])
print(lst0)
# output:
[1, 2, 3, 4]
But somehow this feels a little backward, and it certainly isn't a one-liner. Is there a more pythonic way of doing this?
This is probably blatantly obvious to someone with a more fundamental Python knowledge than myself, and maybe it doesn't even justify a question in itself. But I'm experiencing an increasing curiosity about these things and would like to know if it's possible. And if not, then why?