On Thu, Jun 26, 2008 at 9:27 AM, Danny Laya <[EMAIL PROTECTED]> wrote:
> Hi I'm learning FOR loop now, very easy too learn. But I get confused to
> understand this code :
>
> myList = [1,2,3,4]
> for index in range(len(myList)):
>     myList[index] += 1
> print myList
>
> And the response is:
> [2, 3, 4, 5]
>
> Can you explain me as a newbie, how that code works ??
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

You define a list called myList with 4 integer elements.

>>> type(myList[0])
<type 'int'>

You do a for loop on the four elements.

>>> len(myList)
4

Inside the for loop, you increment each element by one (+= 1).
+= 1 is the same as (variable = variable + 1)

So, just 'play computer' and step through the for loop:
1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5

Thus the output is (2, 3, 4, 5). Still four elements,
each with one added to it.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to