dancow
dancow

Reputation: 3388

In Python, how to slice a list to get the first element, and all elements except the last?

Given:

a = [1, 2, 3]
b = [4,5]

How to get:

[1, 2]
[4]

In the above example, I know this works:

a[:-1]
b[:-1]

However, when:

c = [1]
c[:-1]

The result is an empty list.

Upvotes: 1

Views: 822

Answers (2)

marmeladze
marmeladze

Reputation: 6572

Following JuniorCompressor's answer, if the point is just to remove last element (keep first and if exist others also keep them, but remove last == remove last, if first element is also not the last element). Is it?

>>> def removelast(l):
...     if len(l)>1: del l[len(l)-1]
...     return l
>>> a = range(5)
>>> removelast(a)
[0, 1, 2, 3]
>>> b = [1]
>>> removelast(b)
[1]

Upvotes: 3

JuniorCompressor
JuniorCompressor

Reputation: 20025

You want the following code fragment:

c[:1] + c[1:-1]

For example:

>>> c = [1]
>>> c[:1] + c[1:-1]
[1]

With c[:1] you get a list consisting of the first element (if it exists, otherwise the empty list), and with c[1:-1] you get from the second until the end except the last. If there isn't a second element c[1:-1] will just return the empty list.

Upvotes: 5

Related Questions