# (Very Newbie) Problems defining a variable

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Dec 13 00:47:45 CET 2008

```Kirk Strauser:

> def get_rate(balance):
>    for threshold, rate in ((100000, .0173),
>                            (50000, .0149),
>                            (25000, .0124),
>                            (10000, .0085),
>                            (0, .006)):
>        if balance > threshold:
>            return rate
>    return .0

Nice code. This operation, of choosing an item in a sorted list of
intervals that has no holes, is common enough. But something like an
interval dict is overkill here.
I suggest to put a zero before all those points, to improve
readability and avoid some possible errors: it's easy to not see a

----------------

Bruno Desthuilliers:

> A sequence of pairs and a dict are _almost_ interchangeable (mmm... is
> that the correct word ?) representations of a same data set[1] - the
> main difference being ordering. If ordering matters, choose a sequence
> of pairs as main representation - you can easily build a dict from it
> if/when you need it.

Generally(*) it's better to use the simpler data structure that does
the job. Here a list/tuple of tuples is good.
Very often programs get translated to other languages, so keeping
things as simple as possible helps that too.

---------

(*) I have used 'generally' because there's a compromise to be taken
here.

In C and other related languages you often use structs or records, so
if you have pairs you give a name to the fields, for example "x" and
"y" for the two coordinates of a 2D Point. In Python in such situation
you can create a Point class, but often you instead use a (x, y) or
[x, y]. In some situations you need to access the fields, so you use
[0] and [1]. This is (was) a case where Python looks lower-lever than
the C language. In Python3/Python2.6+ you can use a NamedTuple too.

Is it better to give and take a list of points to/from as a list of
[x,y] lists or as a list of Point2D? Probably a Java programmer thinks
that using Point2D is safer and is a way to document what the function
takes/returns too. Extending the list of pairs to 3D points is a
little simpler if they are represented as tuples/lists.

That's an example where you may not choose the simpler data structure
(that in Python is a list of pairs) and use a list of NamedTuple to
make code "safer" even if the data structure is a little more complex.

Bye,
bearophile

```