What's the pythonic way to repeat first and last element of a list?

1.3k Views Asked by At

If I have a list like [1, 2, 3, 4, 5] what's considered a more pythonic way (if this is not already it) to repeat the first and last elements only and obtain [1, 1, 2, 3, 4, 5, 5]?

What I'm doing right now is:

a = [1, 2, 3, 4, 5]
b = [a[0], *a, a[-1]]
1

There are 1 best solutions below

3
On

I would do the following, which simply glues together three separate lists:

>>> a = [1, 2, 3, 4, 5]
>>> a[:1] + a + a[-1:]
[1, 1, 2, 3, 4, 5, 5]