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.
Asked
Active
Viewed 48 times
-4
-
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
-
3That'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 Answers
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