12

I have a list of unicode values. To the best of my knowledge I can use list[starting location:length to select] to select a range of values from a list, right?

I have a list of 78 unicode values, which are not all unique. When I select a range of 5 values beginning from the 0 position in the list (example: list[0:5]) the correct values are returned. However, when I try to select a range of values that do not begin at the 0 position in the list (example: list[44:5]) then the return is []. Changing the length of the range does not seem to make any difference. Furthermore, if I use list[44], for example, then the value that is returned is correct.

I do not understand why I cannot select from a list when the cursor is not located at 0. Can anyone tell me if lists in python have limitations on how data can be retrieved as a range? I hope my problem and question are clear enough. I would appreciate any feedback. Thanks.

Fisher
  • 245
  • 2
  • 3
  • 6
  • [This question](http://stackoverflow.com/questions/509211/pythons-slice-notation) on how slicing works may be helpful. – DSM Oct 22 '13 at 14:46
  • Thank you, that clears up my misunderstanding about how the slice notation functioned. Your comments were all very useful and I appreciate the help. – Fisher Oct 22 '13 at 15:42
  • Thanks. I'm new to the site and still getting my bearings, but I've checked the answer that was most informative (even though they were all helpful). – Fisher Oct 22 '13 at 16:20

3 Answers3

26

You should do list[44:49] rather than list[44:5]. Usually when you want to fetch 5 items after (including) the a+1th item, you do L[a, a+5]. 'Usually' implies there are more flexible ways to do so: see Extended Slices: http://docs.python.org/release/2.3/whatsnew/section-slices.html.

Also try not to use list as your list name. It overwrites list().

CT Zhu
  • 52,648
  • 17
  • 120
  • 133
9

It is list[starting:ending] not list[starting:length].

So you should do list[44:49]

For more information on slice notation click here

Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
3

In the slice notation [a:b], the second value (b) is not length, but a upper bound.

To get five elements starting from 44 you should use [44:49] (49 = 44 + 5)

If upper bound is smaller than lower bound, you get empty sequence.

falsetru
  • 357,413
  • 63
  • 732
  • 636