Python Forum
Function to count words in a list up to and including Sam
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function to count words in a list up to and including Sam
(Feb-16-2021, 04:25 PM)Serafim Wrote: Note that, if "Sam" is not in the list, you get the length of the list as result.
This, however, gives "None" if "Sam" is missing:
def count_to_sam(samlist):
    if "Sam" not in samlist:
        return None
        return samlist.index("Sam") + 1

lst = ["able","been","state","Sam","beer"]
another_list = ["able","been","state","Tom","beer"]
4 None

Hello Serafim
Thanks for the update, much appreciated and I will study this along with other information that I have received. Thanks again
(Feb-16-2021, 08:02 PM)snippsat Wrote: Is Sam🦄 so special that he need a function that only work for him.
So to give a example of what i mean.
def count_to_name(lst, name):
    count = 0
    for element in lst:
        count += 1
        if element == name:
    return count

if __name__ == '__main__':
    lst = ["able", "been", "state", "Sam", "beer"]
    name = 'been'
    if name not in lst:
        print(f'<{name}> not in list')
        result = count_to_name(lst, name)
        print(f'<{name}> appear at number <{result}> in list')
<been> appear at number <2> in list
You may see the point now and that is more flexible.
Change only name and will get result number or that element is not in list.
name = 'car'
<car> not in list

Oldman45 Wrote:You mention the need for a basic Python tutorial: could you please recommend one?
Here something you can look at.
List of Free Python Resources here
Training sites most start with basic task,as eg Elementary in CheckiO.
Python Exercises, Practice, Solution

Hello Snippsat
That is really helpful, I will certainly study your code and then investigate the links you have kindly provided. Thanks again
(Feb-17-2021, 01:52 AM)jefsummers Wrote:
(Feb-16-2021, 03:55 PM)Oldman45 Wrote: Could you please recommend a learning source as I am really struggling to learn functions? I am currently trying to teach myself from How To Think Like A Computer Scientist.

The Python series from Socratica on Youtube fit my sense of humor. I would also recommend any Youtube video from Ned Batchelder, once you get the basic syntax down, to get a better understanding of name spaces and how it all works.

Here is the Socratica video on functions
Hello jeffsummers
Thanks for your continued support - I think I will enjoy Socratica. Thanks again
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:

def countwhile_inclusive(iterable, predicate):
    for queue_no, item in enumerate(iterable, start=1):
        if item == predicate:
    return queue_no
However, we test all our code, right Wink. 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:
    return queue_no
According 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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  list.count does not appear to function Oldman45 7 455 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  how to create pythonic codes including for loop and if statement? aupres 1 307 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  How to use the count function from an Excel file using Python? jpy 2 342 Dec-21-2020, 12:30 AM
Last Post: jpy
  List of error codes to find (and count) in all files in a directory tester_V 8 515 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Count number of occurrences of list items in list of tuples t4keheart 1 313 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Including modules in Python using sys.path.append JoeDainton123 1 543 Aug-24-2020, 04:51 AM
Last Post: millpond
  Trying to find first 2 letter word in a list of words Oldman45 7 805 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  Including a Variable In the HTML Tags When Sending An Email JoeDainton123 0 365 Aug-08-2020, 03:11 AM
Last Post: JoeDainton123
  how to check if string contains ALL words from the list? zarize 6 803 Jul-22-2020, 07:04 PM
Last Post: zarize
  How to get unique entries in a list and the count of occurrence james2009 3 595 Jun-22-2020, 01:31 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020