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
  Including data files in a package ChrisOfBristol 4 564 Oct-27-2021, 04:14 PM
Last Post: ChrisOfBristol
  Not including a constructor __init__ in the class definition... bytecrunch 3 622 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  count item in list korenron 8 1,146 Aug-18-2021, 06:40 AM
Last Post: naughtyCat
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 670 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  list.count does not appear to function Oldman45 7 1,560 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  how to create pythonic codes including for loop and if statement? aupres 1 801 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  How to use the count function from an Excel file using Python? jpy 2 1,328 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 1,535 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Count number of occurrences of list items in list of tuples t4keheart 1 1,066 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Including modules in Python using sys.path.append JoeDainton123 1 1,227 Aug-24-2020, 04:51 AM
Last Post: millpond

Forum Jump:

User Panel Messages

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