One alternative approach (assumes that if name not in the list then number of words in list should be returned): if the case is to count consecutive items then there is possibility to do that without setting counter outside for loop. Just using built-in function enumerate will suffice:
So we can write:
There is also built-in module itertools which have takewhile which can be used to solve this type of problems as well.
EDIT: this can also be solved using else branch of for loop:
def countwhile_inclusive(iterable, predicate): for queue_no, item in enumerate(iterable, start=1): if item == predicate: break return queue_noHowever, we test all our code, right . By doing so we will find that if iterable is empty we get error (queu_no will be never assigned). So we probably have to deal with it. For that we need to decide what should we return if empty list is passed as argument. There are many possibilities but I point out two of them: raise error or return 0 (in human language it can be described as: 'how many blue marbles do you have?'; 'I don't know what blue marble is (return error); 'I don't have blue marbles (return 0)')
So we can write:
def countwhile_inclusive(iterable, predicate): if len(iterable) == 0: # if list is empty return 0 # or raise ValueError? for queue_no, item in enumerate(iterable, start=1): if item == predicate: break return queue_noAccording to Python wiki getting list length is pretty cheap O(1)
There is also built-in module itertools which have takewhile which can be used to solve this type of problems as well.
EDIT: this can also be solved using else branch of for loop:
def countwhile_inclusive(iterable, predicate): for queue_no, item in enumerate(iterable, start=1): if item == predicate: return queue_no else: # no break return len(iterable)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.