How to Enforce a List Limit in Python

Python lists serve as a foundational data type for programmers used to handling collection of data. Lists can hold a large amount of data (up to millions of data items), but a programmer may wish to limit the number of items contained in the list for the sake of program functionality. This involves tracking the amount of items on a list, and denying any user attempts to add new items beyond the lists determined limit. You can accomplish this most effectively by wrapping your list in a small class, and creating a controller function that mediates how data enters the list.

Things You'll Need

  • Python Interpreter
Show More

Instructions

    • 1

      Create a list wrapper class and an addition function. While lists contain their own functions to add items, you will create a function to control how items are added to the list. The function will take one argument -- the item to add to the list:

      class SpecialList:
      . . . _items = list() //the list
      . . . def addToList(item):
      . . .

    • 2

      Control the flow of the inserted item in the function. First, create an "if" statement that determines if the size of the list exceeds a certain number; in the example, 10. If it does, then the function does not insert the item:

      . . . def addToList(item):
      . . . if len(items) >= 10:
      . . . print "Too Many Items"

    • 3

      Finish the "else" statement. If the length of the list is smaller than 10, then add an item:

      . . . else:
      . . . items.append(item)

Related Searches:

References

Comments

Related Ads

Featured