-2

I am trying to slice a Python list and run into the following error:

>>> a=[2,3,4,5,6,7,8,9]
>>> print(a)
[2, 3, 4, 5, 6, 7, 8, 9]
>>> print(a[0:2])
[2, 3]
>>> print(a[2:2])
[]
>>>
Expected answer: [4,5]

Could someone tell me what I am doing wrong?

EDIT: I figured out my own answer here.

>>> a=[2,3,4,5,6,7,8,9]
>>> print(a)
[2, 3, 4, 5, 6, 7, 8, 9]
>>> print(a[0:2])
[2, 3]
>>> print(a[2:4])
[4, 5]
>>>

n00b mistake!

martineau
  • 119,623
  • 25
  • 170
  • 301
Danny
  • 1
  • 3
  • *why* did you expect that answer? – juanpa.arrivillaga Jul 18 '22 at 15:25
  • I figured out my own answer here. >>> a=[2,3,4,5,6,7,8,9] >>> print(a) [2, 3, 4, 5, 6, 7, 8, 9] >>> print(a[0:2]) [2, 3] >>> print(a[2:4]) [4, 5] >>> n00b mistake! – Danny Jul 18 '22 at 15:30
  • I thought the slicer syntax was i,j where i is the starting position and j is the number of objects to collect – Danny Jul 18 '22 at 15:30
  • It's often helpful to consult the fine [documentation](https://docs.python.org/3/library/functions.html#slice) *before* asking questions here — as well as checking for similar questions on this web site. – martineau Jul 18 '22 at 16:04
  • @martineau I’m just wondering if your comment was as constructive as you thought it was. I wasn’t really sure how to ask the question. I attempted to consult the documentation but I was unable to resolve my query. Have a look at help(list) and see what you get. Python documentation is not exactly known for its ease of access if it were I don’t think we would see so many forums with people asking basic questions. Note to devs: vimtutor is a great intro to vim maybe python should do something similar inside documentation. – Danny Jul 19 '22 at 21:16
  • In this case the documentation describes what each of the up-to-three numbers of a slice mean. There's also an entry for the term **slice** in the [glossary](https://docs.python.org/3/glossary.html#term-slice). One can also play around with them in the Python interactive console. Beyond that, the topic is usually covered in Python tutorials and you can also search for related already asked questions here on this web site — so, in short, I think my comment was spot on. This site's Q&A format was to not meant to replace any of those things. – martineau Jul 19 '22 at 21:41

1 Answers1

2
print(a[2:4])

The second number is end index, not slice length.

Ziming Song
  • 1,176
  • 1
  • 9
  • 22