Takhata101
Takhata101

Reputation: 29

Finding length of list without using the 'len' function in python

In my High school assignment part of it is to make a function that will find the average number in a list of floating points. We can't use len and such so something like sum(numList)/float(len(numList)) isn't an option for me. I've spent an hour researching and racking my brain for a way to find the list length without using the len function, and I've got nothing so I was hoping to be either shown how to do it or to be pointed in the right direction. Help me stack overflow, your my only hope. :)

Upvotes: 0

Views: 6763

Answers (3)

Nabeel Hussain
Nabeel Hussain

Reputation: 16

def length_of_list(my_list):
      if not my_list:
           return 0
      return 1+length_of_list(my_list[1:])

Upvotes: 0

OozeMeister
OozeMeister

Reputation: 4879

Might as well show how to do it with a while loop since it's another opportunity to learn.

Normally, you won't need counter variable(s) inside of a for loop. However, there are certain cases where it's helpful to keep a count as well as retrieve the item from the list and this is where enumerate() comes in handy.

Basically, the below solution is what @Blckknght's solution is doing internally.

def average(items):
    """
        Takes in a list of numbers and finds the average.
    """
    if not items:
        return 0
    # iter() creates an iterator.
    # an iterator has gives you the .next()
    # method which will return the next item
    # in the sequence of items.
    it = iter(items)
    count = 0
    total = 0
    while True:
        try:
            # when there are no more
            # items in the list
            total += next(it)
        # a stop iteration is raised
        except StopIteration:
            # this gives us an opportunity
            # to break out of the infinite loop
            break
        # since the StopIteration will be raised
        # before a value is returned, we don't want
        # to increment the counter until after
        # a valid value is retrieved
        count += 1
    # perform the normal average calculation
    return total / float(count)

Upvotes: 0

Blckknght
Blckknght

Reputation: 104852

Use a loop to add up the values from the list, and count them at the same time:

def average(numList):
    total = 0
    count = 0
    for num in numList:
        total += num
        count += 1

    return total / count

If you might be passed an empty list, you might want to check for that first and either return a predetermined value (e.g. 0), or raise a more helpful exception than the ZeroDivisionError you'll get if you don't do any checking.

If you're using Python 2 and the list might be all integers, you should either put from __future__ import division at the top of the file, or convert one of total or count to a float before doing the division (initializing one of them to 0.0 would also work).

Upvotes: 3

Related Questions