-4

How would you print out the middle values in a list, for example if a list is given [1, 2, 3, 4, 5], the values 2,3,4 would be printed out.

Linoro
  • 1
  • 1
  • You want everything except the first and last element? Does `lst[1:-1]` not work? – The Photon Apr 29 '22 at 00:59
  • No I would only like values that are in the middle of the list for example Given [1, 1, 1, 0, -1, 11, 4] the returned should be 1,1,0,-1,11 – Linoro Apr 29 '22 at 01:00
  • 3
    That's still everything except the first and last element, though... How many elements do you want from the middle? The middle 4 elements, the middle 5 elements? – The Photon Apr 29 '22 at 01:01
  • Thank you for the reminder, I am going to use it now! – Linoro Apr 29 '22 at 01:02
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – Gino Mempin Apr 29 '22 at 08:26

2 Answers2

1

You can do this:

lst = [1, 2, 3, 4, 5]
print(lst[1:-1])
Aly Mobarak
  • 356
  • 2
  • 17
0
lst = list(range(1,6))

lst
Out[2]: [1, 2, 3, 4, 5]

lst[1:-1]
Out[3]: [2, 3, 4]
The Photon
  • 1,242
  • 1
  • 9
  • 12