Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get last and first n elements of a list

Need an answer where numbers to leave from the start and end can easily be adjusted.
Thanks.

This is my code:

ls = [1,2,3,4,5,6]
# desired output: [1,2,5,6]

#Tried the following:
ls[-2:2:1]

ls[2:4:-1]

# Both return empty list

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Code:-

#   [ 0, 1, 2, 3, 4, 5]   for positive indices
lis=[ 1, 2, 3, 4, 5, 6]
#   [-6,-5,-4,-3,-2,-1]  for negative indices
# desired output: [1,2,5,6]

#Some options are
print(lis[:2]+lis[4:])
print(lis[:2]+lis[-2:])
print(lis[-6:-4]+lis[-2:])
print(lis[-6:-4]+lis[4:])

Output:-

[1, 2, 5, 6]
[1, 2, 5, 6]
[1, 2, 5, 6]
[1, 2, 5, 6]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading