Loop Thru A List in Python and Perl

2005-01-18

Python

Here is a example of going thru a list by element.

myList=['one', 'two', 'three', 'infinity']
for item in myList:
     print item

Python provides a way to loop thru a list and give both its index and the item.

myList=['one', 'two', 'three', 'infinity']
for i, v in enumerate(myList):
     print i, v

The following construct loops thru a dictionary, each time assiging both keys and values to variables.

myDict = {'john':3, 'mary':4, 'jane':5, 'vicky':7}
for k, v in myDict.iteritems():
     print k, ' is ', v

Reference: Python Doc↗.

Perl

In Perl, looping thru a list is typically done with “for”:

@myList = ('one', 'two', 'three', 'infinity');
for $element (@myList) {
    print $element, "\n";
}

To loop thru a list using indexs, do like this:

@myList = ('one', 'two', 'three', 'infinity');
for ($i=0; $i < scalar(@myList); $i++) {
    print "$i $myList[$i], ";
} # prints: 0 one, 1 two, 2 three, 3 infinity, 

A typical way to loop thru a hash is:

%myHash = ('john',3, 'mary',4, 'jane',5, 'vicky',7);
for $key (keys %myHash) {
    print "Key and Value pair is: $key, $myHash{$key} \n";
}

Reference: perldoc perldsc↗.


See also:


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet