Python Array Index Error
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with traceback stack in python us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack
Python String Index Without Exception
Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up which of the following lists the position of the error in python Python list.index throws exception when index not found up vote 9 down vote favorite 4 Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this? To me it looks cleaner to deal
List Index Out Of Range Error In Python
with special values, etc than exceptions. EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None? python indexing list share|improve this question edited Apr 23 '15 at 3:59 TopinFrassi 551616 asked Mar 23 '09 at 16:58 Joan Venge 63.3k131338572 add a comment| 10 Answers 10 active oldest votes up vote 10 down vote accepted Because -1 is itself a valid index. It could use a different value, such as None, but that wouldn't be useful, which python valueerror -1 can be in other situations (thus str.find()), and would amount simply to error-checking, which is exactly what exceptions are for. share|improve this answer answered Mar 23 '09 at 17:02 Devin Jeanpierre 39.2k43870 add a comment| up vote 7 down vote To add to Devin's response: This is an old debate between special return values versus exceptions. Many programming gurus prefer an exception because on an exception, I get to see the whole stacktrace and immediate infer what is wrong. share|improve this answer answered Mar 23 '09 at 17:05 phaedrus 9,9661666111 1 This was what I was wondering: special return values versus exceptions. –Joan Venge Mar 23 '09 at 17:06 3 +1: Exceptions don't depend on some value being "sacred". Exceptions are often simpler to work with. –S.Lott Mar 23 '09 at 18:21 The exceptiophobic folks might argue that index not finding an object is not an error, and exceptions should only be used on errors. I am for exceptions in this case. Exceptions can be faster since they don't have to do a check on success. Python prefers exceptions in many cases due to this. In other words, if index finds an object, execution continues with no condition check. If index finds nothing, you are thrown into the catch block with no checks. –Cory B Jun 23 '14 at 23:24 The last comment ignores the fact that the underlying function of course requires to check for the condition(s) that make it fail. T
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn
Valueerror Is Not In List Python
more about Stack Overflow the company Business Learn more about hiring developers or posting
Trace Stack
ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community how do we raise user defined exception in python Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Best way to handle list.index(might-not-exist) in python? up vote 42 http://stackoverflow.com/questions/674229/python-list-index-throws-exception-when-index-not-found down vote favorite 3 I have code which looks something like this: thing_index = thing_list.index(thing) otherfunction(thing_list, thing_index) ok so that's simplified but you get the idea. Now thing might not actually be in the list, in which case I want to pass -1 as thing_index. In other languages this is what you'd expect index() to return if it couldn't find the element. In fact it throws a ValueError. http://stackoverflow.com/questions/2132718/best-way-to-handle-list-indexmight-not-exist-in-python I could do this: try: thing_index = thing_list.index(thing) except ValueError: thing_index = -1 otherfunction(thing_list, thing_index) But this feels dirty, plus I don't know if ValueError could be raised for some other reason. I came up with the following solution based on generator functions, but it seems a little complex: thing_index = ( [(i for i in xrange(len(thing_list)) if thing_list[i]==thing)] or [-1] )[0] Is there a cleaner way to achieve the same thing? Let's assume the list isn't sorted. python list find indexing share|improve this question edited Jan 25 '10 at 14:24 Tim Pietzcker 197k27263354 asked Jan 25 '10 at 13:59 Draemon 21k96395 1 s/catch/except/ :o) –Johannes Charra Jan 25 '10 at 14:20 4 "...in which case I want to pass -1 as thing_index." - This is definitely un-Pythonic. Passing a (meaningless) token value in case an operation does not succeed is frowned upon - exceptions really are the right way here. Especially since thing_list[-1] is a valid expression, meaning the last entry in the list. –Tim Pietzcker Jan 25 '10 at 14:26 @jellybean: facepalm...spot the java coder :P –Draemon Jan 25 '10 at 14:26 3 @Tim: there is str.find method that does exactly that: returns -1 when needl
indexing, which give numpy indexing great power, but with power comes some complexity and the potential for confusion. This section is just an overview http://docs.scipy.org/doc/numpy/user/basics.indexing.html of the various options and issues related to indexing. Aside from single https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html element indexing, the details on most of these options are to be found in related sections. Assignment vs referencing¶ Most of the following examples show the use of indexing when referencing data in an array. The examples work just as well when assigning to an array. See the section in python at the end for specific examples and explanations on how assignments work. Single element indexing¶ Single element indexing for a 1-D array is what one expects. It work exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array. >>> x = np.arange(10) >>> x[2] 2 >>> x[-2] 8 Unlike error in python lists and tuples, numpy arrays support multidimensional indexing for multidimensional arrays. That means that it is not necessary to separate each dimension's index into its own set of square brackets. >>> x.shape = (2,5) # now x is 2-dimensional >>> x[1,3] 8 >>> x[1,-1] 9 Note that if one indexes a multidimensional array with fewer indices than dimensions, one gets a subdimensional array. For example: >>> x[0] array([0, 1, 2, 3, 4]) That is, each index specified selects the array corresponding to the rest of the dimensions selected. In the above example, choosing 0 means that the remaining dimension of length 5 is being left unspecified, and that what is returned is an array of that dimensionality and size. It must be noted that the returned array is not a copy of the original, but points to the same values in memory as does the original array. In this case, the 1-D array at the first position (0) is returned. So using a single index on the returned array, results in a single element being returned. That is: >>> x[0][2] 2 So not
indexing available: field access, basic slicing, advanced indexing. Which one occurs depends on obj. Note In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former. Basic Slicing and Indexing¶ Basic slicing extends Python's basic concept of slicing to N dimensions. Basic slicing occurs when obj is a slice object (constructed by start:stop:step notation inside of brackets), an integer, or a tuple of slice objects and integers. Ellipsis and newaxis objects can be interspersed with these as well. In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any non-ndarray sequence (such as a list) containing slice objects, the Ellipsis object, or the newaxis object, but not for integer arrays or other embedded sequences. The simplest case of indexing with N integers returns an array scalar representing the corresponding item. As in Python, all indices are zero-based: for the i-th index , the valid range is where is the i-th element of the shape of the array. Negative indices are interpreted as counting from the end of the array (i.e., if , it means ). All arrays generated by basic slicing are always views of the original array. The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include: The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step (). This selects the m elements (in the corresponding dimension) with index values i, i + k, ..., i + (m - 1) k where and q and r are the quotient and remainder obtained by dividing j - i by k: j - i = q k + r, so that i + (m - 1) k < j. Example >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x[1:7:2] array([1, 3, 5]) Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension. Negative k makes stepping go towards smaller indices. Example >>> x[-2:10] array([8, 9]) >>> x[-3:3:-1] array([7, 6, 5, 4]) Assume n is the number of elements in the dimension being sliced. Then, if i is not given it defaults to 0 for k > 0 and n - 1 for k < 0 . If j is not given it defaults to n for k > 0 and -1 for k < 0 . If k is not given it defaults to 1. Note that :: is the same as : and means select all indices along this axis. Example >>> x[5:] array([5, 6, 7, 8, 9]) If the number of objects in the s