[Tutor] need futher explaining

bhaaluu bhaaluu at gmail.com
Mon Aug 6 10:30:21 CEST 2007


Greetings,

I'm also a beginner to Python, but I think I can answer
your question. One of the best ways to learn about how
anything in Python works is to use the Python interactive
interpreter, so, away we go (follow along, please):

>>> names = ['anne', 'beth', 'george', 'damon']
>>> print names
['anne', 'beth', 'george', 'damon']
>>> print len(names)
4
>>> print names[0]
anne
>>> print names[3]
damon

1. names is a 'list' which contains four elements
2. The elements in a list are indexed starting with zero (0)
3. So the 'for' loop is iterating the length of the names list len(names)
   which is the same as saying:   for i in range(4):

So len() isn't just for counting characters! It's count will depend
on what 'type' it is counting. In the above case, it is counting elements
in a 'list'.

>>> print len(names[2])
6

names[2] is: g e o r g e
6 characters.
Why?

>>> print type(names[2])
<type 'str'>

george is a string, so len() counts the characters in the string.

I hope this is helpful.
-- 
bhaaluu at gmail dot com


On 8/6/07, Dale Pearl <dale.pearl at gmail.com> wrote:
> I'm reading Beginning Python - From Novice to Professional by Magnus Lie
> Hetland (an Apress book) and there is a code example that I need further
> explaining on to fully grasp.
> There is a section with samle code of:
>   names = ['anne', 'beth', 'george', 'damon']
> ages = [12, 45, 32, 102]
> for i in range(len(names)):
> print names[i], 'is', ages[i], 'years old'
>
> now all of it makes sense to me except for the line for i in
> range(len(names)):
> the len statement calculates the number of characters I'm not quite
> understanding the magic here.
> forgive my stupidity this programming stuff is new to me but if someone
> could explain to me how this single line works it would be greatly
> appreciated.
>
> By the way this is a great book well worth the investment to anyone's
> library who is trying to learn Python.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


More information about the Tutor mailing list