Building lists

Gregory Ewing greg.ewing at canterbury.ac.nz
Mon Oct 20 23:54:55 CEST 2014


Seymore4Head wrote:
> Say I want a
> Grocery list and it will have a maximum size of 50 items.

In Python it's actually easier to deal with variable-sized
lists having no maximum size. Instead of pre-creating a list
of a given size, just start with an empty list and append
things to it.

Unless there's some external reason for a size limit (e.g.
you can't fit more than 50 items in your shopping bag)
there's no need to impose limit at all. You should
certainly start without a limit and only add it later
if needed.

Some things to get you started:

items = [] # Start with an empty list
items.append("cheese") # Add some items to it
items.append("eggs")
items.append("milk")
for item in items: # Process the items
     print(item)

If you really need to limit the number of items, you
can do something like this:

def add_item(item):
     if len(items) < 50:
         items.append(item)
     else:
         raise Exception("Shopping list is full")

-- 
Greg



More information about the Python-list mailing list