I need to call a ValueError in Python

I have this code:

chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse 

I want this to be possible because I don't like it when you throw exceptions:

 chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse 

Is there any way to do this?

+4
source share
3 answers

Note that the latter approach goes against the generally accepted “pythonic” philosophy of EAFP, or “it’s easier to ask forgiveness than permission”. while the first follows him.

+9
source
 if element in mylist: index = mylist.index(element) # ... do something else: # ... do something else 
+7
source

In the specific case, when your list is a sequence of one-character strings, you can get what you want by changing the list to search in the string in advance (for example. '.Join (chars)).

Then you can use the .find () method, which works the way you want. However, there is no appropriate method for lists or tuples.

Another possible option is to use a dictionary. eg.

 d = dict((x, loc) for (loc,x) in enumerate(chars)) ... index = d.get(chars_to_find, -1) # Second argument is default if not found. 

It can also improve if you are doing a lot of queries on the list. If this is just one search on the list, but it is not worth doing.

0
source

Source: https://habr.com/ru/post/1277147/


All Articles