Wednesday, July 16, 2014

How to loop through a python list

Code
mylist = ['apples','bananas', 'oranges']               #1
for item in mylist                                     #2
    print item                                         #3

How this works - Line by Line

mylist = ['apples','bananas', 'oranges']          #1

Creates a list (which i have defined as mylist) of three strings -- apples, bananas, and oranges.
Lists are created by [ ]  and items in the list are separated by commas.  

for item in mylist                                #2
    print item                                    #3
 
These lines loop through the items in the list.  The word 'item' is arbitrary and could be replaced by any other word.  For example, the following would do the same.


for arbitraryword in mylist                                
    print arbitraryword

No comments:

Post a Comment