[Tutor] RE: Thanks for the answers to newB Q: extracting common elements

Sean 'Shaleh' Perry shalehperry@attbi.com
Mon, 24 Jun 2002 16:19:38 -0700 (PDT)


On 24-Jun-2002 Stephen Doughty wrote:
> Hi
> 
> Thanks for the very quick answers everyone, I'll have
> a go at the nested if statements tonight.
> 
> Thanks for pointing out I was talking about
> dictionaries rather than tuples - I'm still getting
> confused between lists, tuples and dictionaries.
> 

a list is a collection of items.  The common use of a list is just what its
name says.  Think of it like a bullet list or a shopping list.  Items in the
list are accessed either directly by index (list[3]) or are iterated over 'for
item in list'.

a tuple is basically a static (or constant) list.  list.append(foo) will add
foo to the list.  There is no way to add an item to a tuple.  So tuples get
used for anything that is created once and not changed.  In python any item
that is constant like this can be used as a dictionary key.  So you could have
a map of x,y coordinates to items.

Which leads us to dictionaries (C++ refers to them as maps, perl calls them
hashes).  Just like a paper dictionary they store a key and its data.  These
are great for address books, real dictionaries, or just about any mapping
structure.

coord = (2,5)
dict[coord] = my_image

for instance would store my image in the dictionary under the key (2,5) which
is a tuple.  This could be used in a graphing program.  dictionary keys are
unique -- there can only be one image at (2,5).  As Jeff Shannon pointed out,
this is used in some algorithms for getting unique values.  Another example is:

uniqs = {}
my_nums = [1, 2, 5, 7, 1, 3, 5]

for num in my_nums:
  uniqs[num] = 1

for num in uniqs.keys():
  print num

outputs:
1
2
5
7
3 (or something like that, you never know what order the keys are in).

When a problem presents itself you just need to ask how am i going to use the
data?  Do I need to access it by some value like a name or a coordinate?  Will
I always just walk the collection from beginning to end?  Does this represent a
map of thing -> other thing or is this more of a generic collection of things?