[Tutor] need futher explaining

Ricardo Aráoz ricaraoz at gmail.com
Thu Aug 9 18:52:02 CEST 2007

bhaaluu wrote:
> 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.

That aside. It would have been better style to write :

for person, age in zip(names, ages):
    print person, 'is', age, 'years old'

zip takes two lists and combines them in a list of tuples which you
assign one by one to person and age in the for.
I guess he does it the way it is because he hasn't come to explain zip()


More information about the Tutor mailing list