[Tutor] list, tuple or dictionary

Wayne Werner waynejwerner at gmail.com
Tue Nov 29 21:49:00 CET 2011

On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY <kellyadrian at hotmail.com>wrote:

>  i am trying to create a program that will allow users to enter items and
> their prices; should i be looking at a list, tuple or what?

The entering part isn't as important as how you want to display the data.
For instance, here's a program that allows the user to input an unlimited
amount of data (using Python 3.x):

while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit',
     input("Enter the price: ")

Of course it doesn't store the data, so it's pretty useless. But it does
allow the user to input whatever they want.

If you wanted to simply create a collection of items you could do it as a
list with alternating values:

    inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.99999999999,
'Spring     Surprise', 0.00]
    for x in range(0, len(inventory)-1, 2):
          print(inventory[x], inventory[x+1])

Or as a list of tuples:

    inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage',
    for item in inventory:
        print(item[0], item[1])

Or a dictionary:

    inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50}
    for item, price in inventory.items():
        print(item, price)

Or if you wanted to get ridiculous, you could go with a list of classes:

class Item:
    def __init__(self, desc='', price=0.00):
        self.desc = desc
        self.price = price
    def __repr__(self):
        return str(self)
    def __str__(self):
        return "{0} - {1}".format(self.desc, self.price)

inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack',
for item in inventory:

It just depends on how complex you want to get!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111129/bc296021/attachment.html>

More information about the Tutor mailing list