1

I know there are similar questions to this one asking for only the first element and the last one, but I think this question is different:

Given a list a=[1,2,3,4,5,6,7,8,9,10], is it possible to write in an elegant form a way to get the first element and the last three (or n) ones in one line in a way such that it returns [8,9,10,1]?

I attempted using a[7:-1], but since it understands as if they were inverted indices, it doesn't work.

I also know it's possible just to do a[len(a)-n:]+[a[0]], but I want to know if there is a 'brackets' way.

3 Answers 3

4

No, there isn't. Concatenating the two slices is the best you can get:

a[-3:] + a[:1]

With some utils, you can at least get this result from a single continuous slice which may simplify some code to calculate the bounding indeces and check for overlaps or staying inbounds:

from itertools import cycle, islice

list(islice(cycle(a), 7, 11))
# [8, 9, 10, 1]

See:

Sign up to request clarification or add additional context in comments.

3 Comments

First one reads much nicer, with -3 and 1. If the array were longer, you'd need to adjust the second solution's numbers or turn them into calculations. And if the array were much longer, the second solution would be much slower.
Not sure about that. The second one covers more general cases: if the negative indexing were to exceed the length or if the resulting slice is longer than the original and you'd have to concatenate more than 2 slices. It also is handy if you know where to start and how many you want and may, thus, remove the need for more complicated calculations. Either way, without knowing, it makes sense to show both.
Yes, I guess both have advantages and disadvantages. Would have to see a generalized problem specification and solutions to really judge them. I do find the speed issue noteworthy, though, as in my experience, many people overlook it.
2

Alternative using itemgetter:

from operator import itemgetter
list(itemgetter(*range(7,10),0)(a))

output:

[8, 9, 10, 1]

1 Comment

whoops, you are right. I did not read your input array properly. my bad. fixed now
0

you cant do a[len(a)-n:]+a[0]

you will get an error

 TypeError: can only concatenate list (not "int") to list 
                                                                                                                      

because a[len(a)-n:] is a list and a[0] is a int

you can do a[len(a)-n:]+a[0:1]

a=[1,2,3,4,5,6,7,8,9,10]
n=3
print(a[(len(a)-n):]+a[0:1])

output:

[8, 9, 10, 1] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.