Home > Software engineering >  Get last and first n elements of a list
Get last and first n elements of a list

Time:12-23

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

CodePudding user response:

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]

CodePudding user response:

yes you can do slicing like ls[:2] ls[-2:] to get the desired output

CodePudding user response:

I read the documentation and tried some codes to see why your code fails.

clearly as shown in the documentation there is no problem with the step of slicing being a negative number. I think the problem is that you can not reach the end of the list (or the beginning if your step is negative) and start from the other side.

And for code to work as you want, you can use ls[:2] ls[-2:] as suggested in the comments

CodePudding user response:

If you don't mind modifying the original list in-place you can also delete the slice in the middle:

del ls[2:4]

ls would then become:

[1, 2, 5, 6]

Demo: https://replit.com/@blhsing/StylishFuzzyCopyrightinfringement

CodePudding user response:

Try ls[2:-2] instead of ls[-2:2]

CodePudding user response:

You can parameterize the code to include how many elements you want from the start and end. For e.g -

ls = [1,2,3,4,5,6]
# desired output: [1,2,5,6]
start = 2 #no of elements needed from start
end = 1 #no of elements needed from end

ls[:start]   ls[-end:] #gives you desired output
  • Related