Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a range of data from a python list [duplicate]

Tags:

python

list

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.

like image 660
Fisher Avatar asked Oct 22 '13 14:10

Fisher


People also ask

How do I find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.


1 Answers

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().

like image 81
CT Zhu Avatar answered Oct 13 '22 08:10

CT Zhu