[Tutor] Sequences of letter

Alan Gauld alan.gauld at btinternet.com
Mon Apr 12 09:25:25 CEST 2010

"Juan Jose Del Toro" <jdeltoro1973 at gmail.com> wrote
> So far this is what I have:
> letras =
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]

Because a string is a sequence of letters you could have saved
some typing by just doing:

letras = "abcdefghijklmnopqrstuvwxyz"

> letra1 = 0
> letra2 = 0
> letra3 = 0

You don't really need these. Remember that a 'for' loop in Python is
really a 'foreach' loop. It will pick out the items in the sequence
itself, you don't need to use an index in most cases.

> for i in letras:
>     for j in letras:
>         for k in letras:
>             print letras[letra1]+letras[letra2]+letras[letra3]

So this becomes:
   print i+j+k

>             letra3=letra3+1

However if you do insist on using indexes you will need to
reset the indexes to 0 at the end of each associated loop.

>     letra2=letra2+1
       letra3 = 0

> letra1=letra1+1
   letra2, letra3=0,0

> It goes all the way to aaz and then it gives me this error
> print letras[letra1]+letras[letra2]+letras[letra3]
> IndexError: list index out of range

Thats because you didn't reset the index to zero so letra3
was already at the end of letras and you tried to add one to
it again pushing it over the edge. This is the reason you
are best to use for loops without indexes, they handle all
that stuff for you.

> Am I even in the right path?

The basic idea is right, you just forgot to reset the
inner index. When debugging this kind of problem
try adding a print line to priont out the variables.
That might have helped you see what was going wrong.

But inthis case it would be better to just forget the indexes
and use the loop variables, i,j,k directly.

> I guess I should look over creating a function or something like that
> because when I run it I can't even use my computer no memory left

Thats shouldn't be a problem, it does not use that much menory!
Unless you have a very small (and old) computer :-)

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list